# 建造者模式
属于创建型模式。
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
主要用于创建一些复杂的对象,这些对象内部构建间的建造顺序通常是稳定的,但对象内部的构建通常面临着复杂的变化。
用户只需要指定需要建造的类型就可以得到它们,如果需要改变一个产品的表示,只需要新创建一个建造者即可。
# 类图
# 代码
# 产品
namespace CreationalPatterns_BuilderPattern | |
{ | |
/// <summary> | |
/// 形状 | |
/// </summary> | |
public class Shape | |
{ | |
/// <summary> | |
/// 形状 | |
/// </summary> | |
public string ShapeName; | |
/// <summary> | |
/// 效果 | |
/// </summary> | |
public string EffectName; | |
/// <summary> | |
/// 颜色 | |
/// </summary> | |
public string ColorName; | |
public void Show() | |
{ | |
Console.WriteLine("Shape:" + ShapeName); | |
Console.WriteLine("Effect:" + EffectName); | |
Console.WriteLine("Color:" + ColorName); | |
} | |
} | |
} |
# 建造者抽象类及其子类
namespace CreationalPatterns_BuilderPattern | |
{ | |
public abstract class ShapeBuilder | |
{ | |
/// <summary> | |
/// 设置形状 | |
/// </summary> | |
protected abstract void SetShape(Shape shape); | |
/// <summary> | |
/// 添加效果 | |
/// </summary> | |
protected abstract void SetEffect(Shape shape); | |
/// <summary> | |
/// 添加颜色 | |
/// </summary> | |
protected abstract void SetColor(Shape shape); | |
/// <summary> | |
/// 返回一个创建完成的对象 | |
/// </summary> | |
/// <returns></returns> | |
public abstract Shape GetShape(); | |
} | |
} |
namespace CreationalPatterns_BuilderPattern | |
{ | |
public class SquareBuilder : ShapeBuilder | |
{ | |
public override Shape GetShape() | |
{ | |
Shape shape = new Shape(); | |
SetShape(shape); | |
SetColor(shape); | |
SetEffect(shape); | |
return shape; | |
} | |
protected override void SetShape(Shape shape) | |
{ | |
shape.ShapeName = "Square"; | |
} | |
protected override void SetColor(Shape shape) | |
{ | |
shape.ColorName = "Red"; | |
} | |
protected override void SetEffect(Shape shape) | |
{ | |
shape.EffectName = "Transparent"; | |
} | |
} | |
} |
namespace CreationalPatterns_BuilderPattern | |
{ | |
public class TriangleBuilder : ShapeBuilder | |
{ | |
public override Shape GetShape() | |
{ | |
Shape shape = new Shape(); | |
SetShape(shape); | |
SetColor(shape); | |
SetEffect(shape); | |
return shape; | |
} | |
protected override void SetShape(Shape shape) | |
{ | |
shape.ShapeName = "Triangle"; | |
} | |
protected override void SetColor(Shape shape) | |
{ | |
shape.ColorName = "Blue"; | |
} | |
protected override void SetEffect(Shape shape) | |
{ | |
shape.EffectName = "Opaque"; | |
} | |
} | |
} |
# 测试
namespace CreationalPatterns_BuilderPattern | |
{ | |
public class Program | |
{ | |
private static void Main() | |
{ | |
ShapeBuilder squareBuilder = new SquareBuilder(); | |
ShapeBuilder triangleBuilder = new TriangleBuilder(); | |
squareBuilder.GetShape().Show(); | |
Console.WriteLine(); | |
triangleBuilder.GetShape().Show(); | |
} | |
} | |
} |
运行结果:
Shape:Square
Effect:Transparent
Color:Red
Shape:Triangle
Effect:Opaque
Color:Blue