此方案的另一個缺點在于,冗余代碼多。在題目所給的環境中,已經說明打印機將與1000臺電腦連接,這么一來,總共就需要寫四千中方法。代碼的重復量是相當大的。我們再來看方案二和方案三,之所以將這兩個方案放在一起討論,是因為他們基本是一個方案(從思想層面上來說),只不過實現手段不同,一個是使用了抽象類,一個是使用了接口,而且最終達到的目的應該是一樣的。
我們先來評價這種方案:首先它解決了代碼冗余的問題,因為可以動態替換打印機,并且都實現了共同的接口,所以不管有多少種移不同類型的打印機,只要一個 Receive方法和一個Print方法,多態性就幫我們解決問題了。而對第一個問題,由于可以運行時動態替換,而不必將打印類編碼在Computer 中,所以有了新的第三方設備,完全可以替換進去運行。這就是所謂的“依賴接口,而不是依賴于具體類”。如此一來,Computer和打印機類的耦合度大大下降。
我們先來看一段斷碼:
1.定義一個接口
namespace _1.InterfaceTest { /// <summary> /// 定義打印機接口,不同類型的打印機都有共同的屬性 /// 他們都會接受電腦的信息(Receive)并且執行打印命令(Print)。 /// </summary> public interface IPrinter { void Receive(); void Print(); } } |
namespace _1.InterfaceTest { /// <summary>
/// 實現A類打印機
/// </summary>
public class PrinterA : IPrinter
{
/// <summary>
/// 實現接口定義的Receive方法
/// </summary>
public void Receive()
{
Console.WriteLine("PrinterA receive message from Computer……");
Console.WriteLine("Receive finished!");
}
/// <summary>
/// 實現接口定義的Print方法
/// </summary>
public void Print()
{
Console.WriteLine("PrinterA execute the Computer command ……");
Console.WriteLine("Print finished!");
}
}
/// <summary>
/// 實現B類打印機
/// </summary>
public class PrinterB : IPrinter
{
/// <summary>
/// 實現接口定義的Receive方法
/// </summary>
public void Receive()
{
Console.WriteLine("PrinterB receive message from Computer……");
Console.WriteLine("Receive finished!");
}
/// <summary>
/// 實現接口定義的Print方法
/// </summary>
public void Print()
{
Console.WriteLine("PrinterB execute the Computer command ……");
Console.WriteLine("Print finished!");
}
}
}
|
namespace _1.InterfaceTest { /// <summary>
/// 電腦與打印機連接,不論是何種打印機,電腦都將調用這兩個方法
/// </summary>
public class Computer
{
/// <summary>
/// 定義接口類型的變量
/// </summary>
private IPrinter _print;
public IPrinter Print
{
get
{
return this._print;
}
set
{
this._print = value;
}
}
public Computer()
{
}
public Computer(IPrinter print)
{
this.Print = print;
}
public void ReceiveData()
{
this._print.Receive();
}
public void PrintData()
{
this._print.Print();
}
}
}
}
|
namespace _1.InterfaceTest
{
class Program
{
static void Main(string[] args)
{
Computer computer = new Computer();
IPrinter printerA = new PrinterA();
IPrinter printerB = new PrinterB();
Console.WriteLine("I connected PrinterA into computer and print something");
computer.Print = printerA;
computer.ReceiveData();
computer.PrintData();
Console.WriteLine("-------------------------------------------------------------“);
Console.WriteLine("Now,PrinterA has some problem!I connected PrinterB into computer and print something");
computer.Print = printerB;
computer.ReceiveData();
computer.PrintData();
}
}
}
|

namespace _1.InterfaceTest
{
class Program
{
static void Main(string[] args)
{
Computer computer = new Computer();
IPrinter newPrinter = new NewPrinter();
Console.WriteLine("I connected newPrinter into computer and print something");
computer.Print = newPrinter;
computer.ReceiveData();
computer.PrintData();
Console.ReadLine();
}
}
}
|

文章列表