一、应用场景
分别用简单工厂设计模式和工厂方法设计模式实现:创建不同品牌的键盘。
#region 简单工厂
public interface IKeyBoard
{
void ShowBrand();
}
public class DellKeyBoard : IKeyBoard
{
public void ShowBrand()
{
Console.WriteLine("我是戴尔键盘"); ;
}
}
public class LenovoKeyBoard : IKeyBoard
{
public void ShowBrand()
{
Console.WriteLine("我是联想键盘");
}
}
public class HPKeyBoard : IKeyBoard
{
public void ShowBrand()
{
Console.WriteLine("我是惠普键盘");
}
}
public class KeyBoardFactory
{
public static IKeyBoard GetKeyBoard(string brand)
{
IKeyBoard kb = null;
switch (brand)
{
case "Dell":
kb = new DellKeyBoard();
break;
case "Lenovo":
kb = new LenovoKeyBoard();
break;
case "HP":
kb = new HPKeyBoard();
break;
default:
break;
}
return kb;
}
}
#endregion
#region 工厂方法
public interface IKeyBoardFactory
{
IKeyBoard GetKeyBoard();
}
public class DellBoardFactory : IKeyBoardFactory
{
public IKeyBoard GetKeyBoard()
{
return new DellKeyBoard();
}
}
public class LenovoBoardFactory : IKeyBoardFactory
{
public IKeyBoard GetKeyBoard()
{
return new LenovoKeyBoard();
}
}
public class HPBoardFactory : IKeyBoardFactory
{
public IKeyBoard GetKeyBoard()
{
return new HPKeyBoard();
}
}
#endregion
二、定义
为了减少创建子类工厂的数量,不必给每一个产品分配一个工厂类,可以将产品进行分组,每组中的不同产品由同一个工厂类的不同方法进行创建。
抽象工厂代码如下:
#region 抽象工厂
//如果要添加鼠标、显示屏等产品
public interface IMouse
{
void ShowMouseBrand();
}
public class DellMouse : IMouse
{
public void ShowMouseBrand()
{
Console.WriteLine("戴尔鼠标"); ;
}
}
public class HPMouse : IMouse
{
public void ShowMouseBrand()
{
Console.WriteLine("惠普鼠标"); ;
}
}
public interface AbstractFactory
{
IKeyBoard GetKeyBoard();
IMouse GetMouse();
}
public class DellFactory : AbstractFactory
{
public IKeyBoard GetKeyBoard()
{
return new DellKeyBoard();
}
public IMouse GetMouse()
{
return new DellMouse();
}
}
public class HPFactory : AbstractFactory
{
public IKeyBoard GetKeyBoard()
{
return new HPKeyBoard();
}
public IMouse GetMouse()
{
return new HPMouse();
}
}
#endregion
三、三种模式的对比
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。