工厂方法模式
有一个OEM制造商代理做HP笔记本电脑(Laptop),后来该制造商得到了更多的品牌笔记本电脑的订单Acer,Lenovo,Dell,该OEM商发现,如果一次同时做很多个牌子的本本,有些不利于管理。利用工厂模式改善设计,用JAVA语言实现
模式UML图
模式代码
Acer.java
public class Acer implements Computer {
@Override
public void computerType() {
System.out.println("电脑的品牌为Acer");
}
}
AcerFactory.java
public class AcerFactory implements ComputerFactory {
@Override
public Computer getComputerType() {
return new Acer();
}
}
Computer.java
public interface Computer {
public void computerType();
}
ComputerFactory.java
public interface ComputerFactory {
public Computer getComputerType();
}
Dell.java
public class Dell implements Computer {
@Override
public void computerType() {
System.out.println("电脑的品牌为Dell");
}
}
DellFactory.java
public class DellFactory implements ComputerFactory {
@Override
public Computer getComputerType() {
return new Dell();
}
}
Lenovo.java
public class Lenovo implements Computer {
@Override
public void computerType() {
System.out.println("电脑的品牌为Lenovo");
}
}
LenovoFactory.java
public class LenovoFactory implements ComputerFactory {
@Override
public Computer getComputerType() {
return new Lenovo();
}
}
Main.java
public class Main {
public static void main(String[] args) {
ComputerFactory factory1=new AcerFactory();
ComputerFactory factory2=new DellFactory();
ComputerFactory factory3=new LenovoFactory();
Computer acer=factory1.getComputerType();
Computer dell=factory2.getComputerType();
Computer lenovo=factory3.getComputerType();
acer.computerType();
dell.computerType();
lenovo.computerType();
}
}
结果截图