实验名称 工厂模式的应用 日期 2019年 03 月25 日
一、实验目的:
1) 掌握工厂模式(Factory)的特点
2) 分析具体问题,使用工厂模式进行设计。
有一个OEM制造商代理做HP笔记本电脑(Laptop),后来该制造商得到了更多的品牌笔记本电脑的订单Acer,Lenovo,Dell,该OEM商发现,如果一次同时做很多个牌子的本本,有些不利于管理。利用工厂模式改善设计,用JAVA语言实现 (或C#控制台应用程序实现)该OEM制造商的工厂模式。绘制该模式的UML图。
二、实验环境:
三、实验内容:
【模式代码(JAVA语言实现)】
package 软件设计体系结构;
public class ComputerTest {
public static void main(String[] args) {
ComputerFactory computerFactory1 = new DellFactory();
Computer computer1 = computerFactory1.getComputerType();
computer1.computerType();
ComputerFactory computerFactory2 = new LenovoFactory();
Computer computer2 = computerFactory2.getComputerType();
computer2.computerType();
ComputerFactory computerFactory3 = new AcerFactory();
Computer computer3 = computerFactory3.getComputerType();
computer3.computerType();
}
}
package 软件设计体系结构;
public class Acer implements Computer {
public void computerType(){
System.out.println("产生一台Acer电脑");
}
}
package 软件设计体系结构;
public class AcerFactory implements ComputerFactory {
public Computer getComputerType(){
return new Acer();
}
}
package 软件设计体系结构;
public interface Computer {
public void computerType();
}
package 软件设计体系结构;
public interface ComputerFactory {
Computer getComputerType();
}
package 软件设计体系结构;
public class Dell implements Computer {
public void computerType(){
System.out.println("产生一台Dell电脑");
}
}
package 软件设计体系结构;
public class DellFactory implements ComputerFactory {
public Computer getComputerType(){
return new Dell();
}
}
package 软件设计体系结构;
public class Lenovo implements Computer {
public void computerType(){
System.out.println("产生一台Lenovo电脑");
}
}
package 软件设计体系结构;
public class LenovoFactory implements ComputerFactory {
public Computer getComputerType(){
return new Lenovo();
}
}
【运行截图】