简单工厂+抽象工厂
抽象工厂的一个很简单的应用,这久公i司的项目中可能用到不同的打印机,不同的打印机可能打印方法有所改变,自己优化了下原来的代码:
打印接口:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
interface Iprint
{
void Print();
}
实现接口的USB打印机类:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
public class UsbPrinter:Iprint
{
#region Iprint 成员
public void Print()
{
Console.WriteLine("I am UsbPrinter");
}
#endregion
}
实现接口的COM口打印机类:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
public class ComPrinter:Iprint
{
#region Iprint 成员
public void Print()
{
Console.WriteLine("I am ComPrinter");
}
#endregion
}
工厂类:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
class PrinterHandle
{
private static string PrintType = System.Configuration.ConfigurationManager.AppSettings["printerType"];
public static Iprint GetPrinter()
{
switch (PrintType)
{
case "usb":
return new UsbPrinter();
break;
case "com":
return new ComPrinter();
break;
default:
return new UsbPrinter();
break;
}
}
}
客户端调用:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
PrinterHandle.GetPrinter().Print();
配置文件:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="printerType" value="com"/>
</appSettings>
</configuration>
呵呵,很简单的应用,但是感觉结构清晰了好多,便于维护。