工厂方法模式
1.什么是工厂方法模式
个人理解:工厂方法模式是在简单工厂模式之上的,避免了开闭原则的问题,增加了扩展功能,更灵活一些。
2.分析
工厂方法模式包括了四部分:
1.抽象工厂
2.具体工厂
3.抽象产品
4.具体产品
举例分析更好说明这四个部分:
例如:多个牌子的厂子生产对应牌子的电脑
牌子:DELL ACER
抽象工厂就是factory
具体工厂就是DELLfactory、ACERfactory
抽象产品就是笔记本电脑computer
具体产品就是DELLcomputer,ACERcomputer
3.图解
添加新产品之前:
添加新产品之后:
可以扩展,符合开闭原则
4.源代码(扩展之前)
interface Laptop{
void LaptopInfo(); //笔记本信息
}
class DellLaptop implements Laptop{
@Override
public void LaptopInfo() {
// TODO Auto-generated method stub
System.out.println("DELL Info");
}
}
class AcerLaptop implements Laptop{
@Override
public void LaptopInfo() {
// TODO Auto-generated method stub
System.out.println("Acer Info");
}
}
interface Factory{
Laptop produce(); //抽象工厂
}
class DellFactory implements Factory{
@Override
public Laptop produce() {
// TODO Auto-generated method stub
return new DellLaptop();
}
}
class AcerFactory implements Factory{
@Override
public Laptop produce() {
// TODO Auto-generated method stub
return new AcerLaptop();
}
}
public class factorymethod {
public static void main(String[] args) {
Factory f = new DellFactory();
f.produce().LaptopInfo();
f = new AcerFactory();
f.produce().LaptopInfo();
}
}
运行结果:
DELL Info
Acer Info
现在想加入一个Lenovo电脑:
class LenovLaptop implements Laptop{
@Override
public void LaptopInfo() {
// TODO Auto-generated method stub
System.out.println("Lenov Info");
}
}
class LenovFactory implements Factory{
@Override
public Laptop produce() {
// TODO Auto-generated method stub
return new LenovLaptop();
}
}
main中添加:
f = new LenovFactory();
f.produce().LaptopInfo();
运行结果:
DELL Info
Acer Info
Lenov Info
5.工厂方法模式优点与缺点
优点:1.具有和简单工厂模式的优点,修改类名,客户端不知道
2.扩展新的产品时,只需要额外添加一个新的工厂,无需修改源代码,遵循了开闭原则。
缺点:若新的产品等级很多,那么就会添加很多个工厂,代码量大
———————————————————————————————————
PS:若有什么错误,希望大家能指出来,第一次学可能懂得还不多,错误难免,望见谅