建造者模式包含4个角色:
指挥者、抽象建造者、具体建造者、产品
构建者模式基本代码如下,可参考:
// 产品类
class Product {
IList<string> parts = new List<string>();
public void Add(string part) {
parts.add(part);
}
public void Show() {
Console.WriteLine("产品创建");
foreach(string part in parts) {
Console.WriteLine(part);
}
}
}
// 抽象建造者类
abstract class Builder {
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product getProduct();
}
// 具体建造者
class ConcreteBuilder1 : Builder {
private Product product = new Product();
public override void BuildPartA() {
product.add("部分A");
}
public override void BuildPartB() {
product.add("部分B");
}
public override void getProduct() {
return product;
}
}
class ConcreteBuilder2 : Builder {
private Product product = new Product();
public override void BuildPartA() {
product.add("部件x");
}
public override void BuildPartB() {
product.add("部件y");
}
public override void getProduct() {
return product;
}
}
// 指挥者类
class Director {
public void Construct(Builder builder) {
builder.BuildPartA();
builder.BuildPartB();
}
}
// 客户端
static void Main(string[] args) {
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
director.Construct(b1);
Product p1 = b1.getProduct();
p1.Show();
director.Construct(b2);
Product p2 = b2.getProduct();
p2.Show();
}
// 套餐类
public class Meal {
private String food;
private String drink;
// 省略get set方法
}
public abstract class MealBuilder {
Meal meal = new Meal();
public abstract void buildFood();
public abstract void buildDrink();
public Meal getMeal() {
return meal;
}
}
// 套餐A
public class MealA extends MealBuilder {
public void buildDrink(){
meal.setDrink("一杯可乐");
}
public void buildFood(){
meal.setFood("一盒薯条");
}
}
// KFC服务员相当于指挥者
public class KFCWaiter {
private MealBuilder mealBuilder;
public void setMealBuilder(MealBuilder mealBuilder) {
this.mealBuilder = mealBuilder;
}
public Meal construct() {
mealBuilder.buildFood();
mealBuilder.buildDrink();
return mealBuilder.getMeal();
}
}
public class Client{
public static void main(String [] args){
KFCWaiter waiter = new KFCWaiter();
MealA a = new MealA();
// 服务员准备套餐A
waiter.setMealBuilder(a);
Meal mealA = waiter.construct();
}
}
优点:
- 将复杂产品的创建步骤分解在不同的方法中,使得创建更加清晰,
- 将产品的创建过程与产品本身分离开来,可以使用相同的创建过程来得到不同的产品
缺点:
- 所创建产品有较多共同点,如果产品间差异较大,则不适合建造者模式,使用范围受限,
- 如果产品内部变化复杂,可能会导致需要定义很多具体建造者来适应这种变化,系统变得很庞大。