组装电脑,不管是台式机还是笔记本电脑,里面都是由主板,内存,硬盘,CPU,显示器组成等。由此,便想到了我们设计模式里面的建筑者模式。建筑者(Builder)模式是将一个复杂对象的构造与它分离,使同样的过程可以创建不同的表示。
我们来看下UML类图
我们先定义一个Computer接口,把电脑主要骨架定义下来。接下来台式机与笔记本都实现该Computer.Person里面有个assmely方法。来看看具体实现
package com.tankiy.Build;
/**
* <p>Title: Build(建筑者模式)</p>
* @author Tankiy
* @version 1.0
*/
public interface Computer {
public void cpu();
public void memory();
public void hardDisk();
public void monitor();
public void motherBoard();
}
package com.tankiy.Build;
/**
* <p>Title: Build(建筑者模式)</p>
* @author Tankiy
* @version 1.0
*/
public class NotebookComputer implements Computer {
public void cpu() {
System.err.println("笔记本CPU!");
}
public void hardDisk() {
System.err.println("2.5硬盘!");
}
public void memory() {
System.err.println("笔记本内存DDR3!");
}
public void monitor() {
System.err.println("显示屏!");
}
public void motherBoard() {
System.err.println("笔记本主板!");
}
}
package com.tankiy.Build;
/**
* <p>Title: Build(建筑者模式)</p>
* @author Tankiy
* @version 1.0
*/
public class DeskTopComputer implements Computer {
public void cpu() {
System.err.println("台式CPU!");
}
public void hardDisk() {
System.err.println("3.5硬盘!");
}
public void memory() {
System.err.println("台式内存DDR3!");
}
public void monitor() {
System.err.println("21寸显示器!");
}
public void motherBoard() {
System.err.println("台式主板!");
}
}
package com.tankiy.Build;
/**
* <p>Title: Build(建筑者模式)</p>
* @author Tankiy
* @version 1.0
*/
public class Person {
private Computer computer;
public Person(Computer computer) {
this.computer = computer;
}
public void assmely() {
computer.cpu();
computer.memory();
computer.hardDisk();
computer.monitor();
computer.motherBoard();
}
}
package com.tankiy.Build;
import junit.framework.TestCase;
/**
* <p>Title: Build(建筑者模式)</p>
* @author Tankiy
* @version 1.0
*/
public class BuildTest extends TestCase {
public void testBuild() {
Person jack = new Person(new DeskTopComputer());
jack.assmely();
System.err.println("=========");
Person tankiy = new Person(new NotebookComputer());
tankiy.assmely();
}
}
结果如下
台式CPU!
台式内存DDR3!
3.5硬盘!
21寸显示器!
台式主板!
=========
笔记本CPU!
笔记本内存DDR3!
2.5硬盘!
显示屏!
笔记本主板!