设计模式学习笔记四——Builder模式
动机:一个复杂对象由多个子对象构成,该对象创建的算法相对不变,构成的子对象剧烈变化。如何应对子对象的剧烈变化,隔离比较稳定的创建算法和易变的子对象,使客户程序不随着子对象的改变而改变。
场景:ThinkPad系列产品和一般笔记本一样,拥有比较固定的组成部分:主板、CPU、硬盘、显示器、键盘……。假设所有ThinkPad的组装过程完全相同,不同性能参数的部分组合在一起形成不同型号的ThinkPad,比如T43和T60。如何在组装过程不变的情况下,做出适合型号的所需部件(以CPU和主板为例),就能快速组装成我们所要型号的ThinkPad?
结构
代码实现
/**//*
* 子对象CPU
*/
namespace DesignPattern.Builder
{
public abstract class CPU
{
}
public class T43CPU : CPU
{
}
public class T60CPU : CPU
{
}
}
* 子对象CPU
*/
namespace DesignPattern.Builder
{
public abstract class CPU
{
}
public class T43CPU : CPU
{
}
public class T60CPU : CPU
{
}
}
/**//*
* 子对象主板
*/
namespace DesignPattern.Builder
{
public abstract class Mainboard
{
}
public class T43Mainboard : Mainboard
{
}
public class T60Mainboard : Mainboard
{
}
}
* 子对象主板
*/
namespace DesignPattern.Builder
{
public abstract class Mainboard
{
}
public class T43Mainboard : Mainboard
{
}
public class T60Mainboard : Mainboard
{
}
}
/**//*
*复杂对象ThinkPad
*/
namespace DesignPattern.Builder
{
public abstract class ThinkPad
{
}
public class T43ThinkPad : ThinkPad
{
}
public class T60ThinkPad : ThinkPad
{
}
}
*复杂对象ThinkPad
*/
namespace DesignPattern.Builder
{
public abstract class ThinkPad
{
}
public class T43ThinkPad : ThinkPad
{
}
public class T60ThinkPad : ThinkPad
{
}
}
/**//*
* ThinkPad生成器
*/
namespace DesignPattern.Builder
{
public abstract class ThinkPadBuilder
{
public abstract CPU BuildCPU();
public abstract Mainboard BuildMainboard();
public abstract ThinkPad GetThinkPad();
}
public class T43Builder : ThinkPadBuilder
{
public override CPU BuildCPU()
<img id=Codehighlighter1_629_672_Closed_Image style="DISPLAY: none" onclick="this.style.display='none'; Codehighlighter1_629_672_Closed_Text.style.display='none'; Codehigh
* ThinkPad生成器
*/
namespace DesignPattern.Builder
{
public abstract class ThinkPadBuilder
{
public abstract CPU BuildCPU();
public abstract Mainboard BuildMainboard();
public abstract ThinkPad GetThinkPad();
}
public class T43Builder : ThinkPadBuilder
{
public override CPU BuildCPU()
<img id=Codehighlighter1_629_672_Closed_Image style="DISPLAY: none" onclick="this.style.display='none'; Codehighlighter1_629_672_Closed_Text.style.display='none'; Codehigh