工厂模式——活雷锋
定义
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
UML图
与简单工厂的区别
简单工厂模式的工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类。对于客户端来说,去除了与具体产品的依赖。想要加功能,需要修改工厂类。
工厂类需要客户端决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的。想要加功能,需要修改客户端。
简单工厂模式的工厂类如果要添加、删除或修改功能类,会把所有功能类暴露,违背开放-关闭原则。
工厂类只需要开放需要修改的类,不会暴露其他细节,符合开放-关闭原则。
用例——计算器
同样实现计算器
构建工厂接口
interface IFactory{
abstract Operation CreateOperation();
}
加减乘除各建一个具体工厂实现接口
public class AddFactory implements Factory{
public Operation createOperation(){
return new OperationAdd();
}
}
public class SubFactory implements Factory{
public Operation createOperation(){
return new OperationSub();
}
}
public class MulFactory implements Factory{
public Operation createOperation(){
return new OperationMul();
}
}
public class DivFactory implements Factory{
public Operation createOperation(){
return new OperationDiv();
}
}
客户端
IFactory operFactory = new AddFactory();
Operation oper = operFactory.createOperation();
oper.setNumberA = 1;
oper.SetNumberB = 3;
double result = oper.getResult();
UML图
用例——雷锋工厂
需要实现一个学雷锋的大学生和社区的志愿者帮助老人的系统。
雷锋类
class Leifeng{
public void sweep(){
System.out.println("扫地");
}
public void wash(){
System.out.println("洗衣");
}
public void buyRice(){
System.out.println("买米");
}
}
具体的雷锋
class Undergraduate extends LeiFeng{}
class Volunteer extends LeiFeng{}
雷锋工厂
interface IFactory{
LeiFeng createLeiFeng();
}
class UndergraduateFactory implements IFactory{
public LeiFeng createLeiFeng(){
return new Undergraduate();
}
}
class VolunteerFactory implements IFactory{
public LeiFeng createLeiFeng(){
return new Volunteer();
}
}
客户端
IFactory factory = new UndergraduateFactory();
LeiFeng student = factory.createLeiFeng();
student.sweep();
student.wash();
student.buyRice();