软件设计模式与体系结构 实验一 工厂方法模式
【实验内容和要求】
有一个OEM制造商代理做HP笔记本电脑(Laptop),后来该制造商得到了更多的品牌笔记本电脑的订单Acer,Lenovo,Dell,该OEM商发现,如果一次同时做很多个牌子的本本,有些不利于管理。利用工厂模式改善设计,用JAVA语言实现 (或C#控制台应用程序实现)该OEM制造商的工厂模式。绘制该模式的UML图。
一、实验目的:
1) 掌握工厂模式(Factory)的特点
2) 分析具体问题,使用工厂模式进行设计。
二、实验环境:
Eclipse
三、实验内容:
【模式UML图】
【模式代码(JAVA语言实现)】
public class FactoryMethod {
public static void main(String[] args) {
Computer c = null;
Factory f = null;
f = new DellFactory();
c = f.getComputerType();
c.ComputerType();
f = new LenovoFactory();
c = f.getComputerType();
c.ComputerType();
f = new AcerFactory();
c = f.getComputerType();
c.ComputerType();
}
}
interface Factory{
Computer getComputerType();
}
class DellFactory implements Factory{
@Override
public Computer getComputerType() {
return new Dell();
}
}
class AcerFactory implements Factory{
@Override
public Computer getComputerType() {
return new Acer();
}
}
class LenovoFactory implements Factory{
@Override
public Computer getComputerType() {
return new Lenovo();
}
}
interface Computer{
public void ComputerType();
}
class Dell implements Computer{
@Override
public void ComputerType() {
System.out.println("Dell Computer");
}
}
class Acer implements Computer{
@Override
public void ComputerType() {
System.out.println("Acer Computer");
}
}
class Lenovo implements Computer{
@Override
public void ComputerType() {
System.out.println("Lenovo Computer");
}
}
【运行截图】
四、心得体会:
通过本次实验,我学会了使用工厂方法模式。工程方法模式的适用性如下:
- 当一个类不知道它所必须创建的对象的类时。
- 当一个类希望由它的子类来指定它所创建的对象时。
- 当类将创建对象的职责委托给多个帮助子类中的某一个,并希望将 哪一个帮助子类是代理这一信息局部化时。