/*
Learning C#
by Jesse Liberty
Publisher: O'Reilly
ISBN: 0596003765
*/
using System;
namespace InterfaceDemo
{
interface IStorable
{
void Read();
void Write(object obj);
int Status { get; set; }
}
// the Compressible interface is now the
// base for ILoggedCompressible
interface ICompressible
{
void Compress();
void Decompress();
}
// extend ICompressible to log the bytes saved
interface ILoggedCompressible : ICompressible
{
void LogSavedBytes();
}
// Document implements both interfaces
class Document : IStorable, ILoggedCompressible
{
// the document constructor
public Document(string s)
{
Console.WriteLine("Creating document with: {0}", s);
}
// implement IStorable
public void Read()
{
Console.WriteLine(
"Implementing the Read Method for IStorable");
}
public void Write(object o)
{
Console.WriteLine(
"Implementing the Write Method for IStorable");
}
public int Status
{
get { return status; }
set { status = value; }
}
// implement ICompressible
public void Compress()
{
Console.WriteLine("Implementing Compress");
}
public void Decompress()
{
Console.WriteLine("Implementing Decompress");
}
// implement ILoggedCompressible
public void LogSavedBytes()
{
Console.WriteLine("Implementing LogSavedBytes");
}
// hold the data for IStorable's Status property
private int status = 0;
}
public class TesterISAS
{
public void Run()
{
Document doc = new Document("Test Document");
// cast using as, then test for null
IStorable isDoc = doc as IStorable;
if (isDoc != null)
{
isDoc.Read();
}
else
{
Console.WriteLine("Could not cast to IStorable");
}
ILoggedCompressible ilDoc = doc as ILoggedCompressible;
if (ilDoc != null)
{
Console.Write("\nCalling both ICompressible and ");
Console.WriteLine("ILoggedCompressible methods...");
ilDoc.Compress();
ilDoc.LogSavedBytes();
}
else
{
Console.WriteLine("Could not cast to ILoggedCompressible");
}
// cast using as, then test for null
ICompressible icDoc = doc as ICompressible;
if (icDoc != null)
{
Console.WriteLine(
"\nTreating the object as Compressible... ");
icDoc.Compress();
}
else
{
Console.WriteLine("Could not cast to ICompressible");
}
}
[STAThread]
static void Main()
{
TesterISAS t = new TesterISAS();
t.Run();
}
}
}