组装电脑之Builder模式

    组装电脑,不管是台式机还是笔记本电脑,里面都是由主板,内存,硬盘,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硬盘!

显示屏!

笔记本主板!


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值