五分钟一个设计模式,用最简单的方法来描述设计模式。
认识创建者模式
创建者模式(又叫生成器模式)是为创建一个产品而生的,这个产品的组装算法是确定的,但零部件可以分配给多个厂商生产。使用创建者模式来创建产品,可以把产品零部件的生产和组装分开了。
创建者模式包含以下几个部分:
- 产品(Product)
- 厂商的接口(Builder)
- 具体的厂商(ConcreteBuilder1、ConcreteBuilder2、…ConcreteBuilderN),实现厂商接口,负责产品零部件的生产工作
- 指导者(Director),这家伙知道怎么组装产品,负责整个产品的构建算法
示例代码
//产品
public class Product
{
public string ProductPartA { get; set; }
public string ProductPartB { get; set; }
public string ProductPartC { get; set; }
public override string ToString()
{
return ProductPartA + "\n" + ProductPartB + "\n" + ProductPartC;
}
}
//厂商的接口
public interface Builder
{
void BuildePartA();
void BuildePartB();
void BuildePartC();
Product GetProduct();
}
//具体厂商1
public class ConcreteBuilder1:Builder
{
Product product = new Product();
public void BuildePartA()
{
product.ProductPartA = "part A, concreteBuilder1 制造";
}
public void BuildePartB()
{
product.ProductPartB = "part B, concreteBuilder1 制造";
}
public void BuildePartC()
{
product.ProductPartC = "part C, concreteBuilder1 制造";
}
public Product GetProduct()
{
return product;
}
}
//具体厂商2
public class ConcreteBuilder2 : Builder
{
Product product = new Product();
public void BuildePartA()
{
product.ProductPartA = "part A, concreteBuilder2 制造";
}
public void BuildePartB()
{
product.ProductPartB = "part B, concreteBuilder2 制造";
}
public void BuildePartC()
{
product.ProductPartC = "part C, concreteBuilder2 制造";
}
public Product GetProduct()
{
return product;
}
}
//指导者
public class Director
{
private Builder builder;
public Director(Builder builder)
{
this.builder = builder;
}
//组装产品的算法。将具体厂商生产的零部件组装到一起(可以加入特定的业务逻辑)
public void Construct()
{
builder.BuildePartA();
builder.BuildePartB();
builder.BuildePartC();
Product p = builder.GetProduct();
Console.WriteLine(p.ToString());
}
}
下面是场景类
class Program
{
static void Main(string[] args)
{
Builder builder1=new ConcreteBuilder1();
Builder builder2=new ConcreteBuilder2();
Director director = new Director(builder1);
director.Construct();
director = new Director(builder2);
director.Construct();
}
}
运行结果:
part A, concreteBuilder1 制造
part B, concreteBuilder1 制造
part C, concreteBuilder1 制造
part A, concreteBuilder2 制造
part B, concreteBuilder2 制造
part C, concreteBuilder2 制造
时间: 2024-10-07 09:30:35