创建者模式,主要针对某些产品有类似的生产步骤,且有需要有先后顺序的进行各个部件的生成。
一、示例展示:
通过学习及总结,以下是我完成的创建者模式的示例:
1.创建产品类:Laptop
public class Laptop { ArrayList LaptopParts = new ArrayList(); public void AddParts(string PartName) { LaptopParts.Add(PartName); } public void ShowPartList() { foreach (string part in LaptopParts) { Console.WriteLine(part); } } }
2. 创建抽象创建者角色:AbstractBuilder
public abstract class AbstractBuilder { public abstract void CreateCPU(); public abstract void CreateScreen(); public abstract void CreateKeyboard(); public abstract Laptop GetLaptop(); }
3. 创建具体创建者角色:AppleLaptopBuilder
public class AppleLaptopBuilder : AbstractBuilder { private Laptop laptop = new Laptop(); public override void CreateCPU() { laptop.AddParts("Apple CPU is very fast!"); } public override void CreateKeyboard() { laptop.AddParts("The experience of apple Keyboard is wouderful!"); } public override void CreateScreen() { laptop.AddParts("The experience of apple screen is really amazing!"); } public override Laptop GetLaptop() { return laptop; } }
4. 创建具体创建者角色:LenovoLaptopBuilder
public class LenovoLaptopBuilder : AbstractBuilder { private Laptop laptop = new Laptop(); public override void CreateCPU() { laptop.AddParts("Lenovo CPU is very good!"); } public override void CreateKeyboard() { laptop.AddParts("Lenovo Keyboard looks amazing!"); } public override void CreateScreen() { laptop.AddParts("Lenovo screen is wounderful!"); } public override Laptop GetLaptop() { return laptop; } }
5. 创建指导者角色:Director
public class Director { public void Construct(AbstractBuilder builder) { builder.CreateCPU(); builder.CreateKeyboard(); builder.CreateScreen(); builder.GetLaptop(); } }
6. 定义客户端调用:
class Program { static void Main(string[] args) { Director director = new Director(); AppleLaptopBuilder alBuilder = new AppleLaptopBuilder(); director.Construct(alBuilder); Laptop AppLaptop = alBuilder.GetLaptop(); AppLaptop.ShowPartList(); LenovoLaptopBuilder llBuilder = new LenovoLaptopBuilder(); director.Construct(llBuilder); Laptop LnLaptop = llBuilder.GetLaptop(); LnLaptop.ShowPartList(); Console.ReadLine(); } }
二、创建者模式设计理念:
通过抽象创建者角色来限制及规范产品的结构,且针对产品的每个部件都需要相应的建构方法。具体的创建者角色负责创建产品的实例,在这个过程中间,指导者的角色负责创建产品的实例的具体步骤(可以随产品的具体创建步骤而增加或减少)。
三、角色及关系: