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