抽象产品角色
//鼠标抽象类 public abstract class Mouse { public abstract void Print(); }
具体产品角色
//戴尔鼠标 public class DellMouse : Mouse { public override void Print() { Console.WriteLine("生产了一个Dell鼠标"); } }
//惠普鼠标 public class HPMouse : Mouse { public override void Print() { Console.WriteLine("生产了一个惠普鼠标"); } }
//联想鼠标 public class LenovoMouse : Mouse { public override void Print() { Console.WriteLine("生产了一个联想鼠标"); } }
工厂角色
public class MouseFachtory { private Mouse mouse = null; public Mouse CreateMouse(string brand) { switch (brand) { case "dell": mouse=new DellMouse(); break; case "hp": mouse = new HPMouse(); break; case "lenovo": mouse = new LenovoMouse(); break; default: break; } return mouse; } }
运行测试
MouseFachtory mouseFachtory = new MouseFachtory(); var mouse1 = mouseFachtory.CreateMouse("dell"); var mouse2 = mouseFachtory.CreateMouse("dell"); var mouse3 = mouseFachtory.CreateMouse("dell"); var mouse4 = mouseFachtory.CreateMouse("hp"); var mouse5 = mouseFachtory.CreateMouse("hp"); var mouse6 = mouseFachtory.CreateMouse("lenovo"); mouse1.Print(); mouse2.Print(); mouse3.Print(); mouse4.Print(); mouse5.Print(); mouse6.Print();