设计模式-我用工厂模式卖水果
工厂类用在需要创建对象的业务逻辑中, 返回不同的对象, 比如: 我要生产一个水果:
简单工厂
父类或接口:
/**
* @author xinruoxiangyang9010
*/
public interface Fruit {
String getFruitName();
}
产品子类:
public class Apple implements Fruit {
@Override
public String getFruitName() {
return "我是苹果";
}
}
public class Orange implements Fruit {
@Override
public String getFruitName() {
return "我是橘子";
}
}
生产产品的工厂类:
/**
* @author xinruoxiangyang9010
*/
public class FruitFactory {
public static Fruit getFruit(String fruitType) {
switch (fruitType) {
case "apple":
return new Apple();
case "orange":
return new Orange();
default:
return null;
}
}
}
客户端使用:
/**
* @author xinruoxiangyang9010
* 工厂模式使用
*/
public class FruitProduce {
public static void main(String[] args) {
Fruit fruit1 = FruitFactory.getFruit("apple");
// 结果:我是苹果
System.out.println(fruit1.getFruitName());
// 第二个使用场景
Fruit fruit2 = FruitFactory.getFruit("orange");
// 结果:我是橘子
System.out.println(fruit2.getFruitName());
}
}
小结:
编写水果类, 都实现接口Fruit, 在业务扩展时新增水果类
水果实例化由FruitProduce统一管理, 业务扩展时, 只需要修改FruitProduce即可
传入对应的类型即可获取对应的水果
缺点是, 当业务扩展时, 没有达到只增不改的效果(不符合开闭原则)
工厂模式
现在需要进行产品升级, 不仅仅只要水果, 而是要一个果盘
产品介绍:
/**
* @author xinruoxiangyang9010
*/
public interface Fruit {
/**
* 水果简介
* @return
*/
String getFruitName();
/**
* 加工流程
*/
void process();
/**
* 打包方法
*/
void doPackage();
}
public class Apple implements Fruit {
@Override
public String getFruitName() {
return "我是一盒苹果, 已经削皮切块, 定价8块8";
}
@Override
public void process() {
System.out.println("苹果进行削皮,切块");
}
@Override
public void doPackage() {
System.out.println("用一个绿色的盒子装上");
}
}
public class Orange implements Fruit {
@Override
public String getFruitName() {
return "我是橘子果盘, 已经切好, 售价9块9";
}
@Override
public void process() {
System.out.println("不用扒皮, 切块就行");
}
@Override
public void doPackage() {
System.out.println("用一个橙色的盒子进行打包, 一看就是橘子");
}
}
加工产品的工厂类:
/**
* @author xinruoxiangyang9010
*/
public interface BoxFactory {
Fruit getFruit();
}
public class AppleFactory implements BoxFactory {
@Override
public Fruit getFruit() {
return new Apple();
}
}
public class OrangeFactory implements BoxFactory{
@Override
public Fruit getFruit() {
return new Orange();
}
}
/**
* @author xinruoxiangyang9010
*/
public class FruitBoxStore {
private BoxFactory boxFactory;
public FruitBoxStore(BoxFactory box) {
boxFactory = box;
}
public Fruit getFruitBox() {
Fruit fruit = boxFactory.getFruit();
fruit.process();
fruit.doPackage();
return fruit;
}
}
出售产品的时候到了:
/**
* @author xinruoxiangyang9010
* 工厂模式使用
*/
public class FruitProduce {
public static void main(String[] args) {
FruitBoxStore fruitBoxStore1 = new FruitBoxStore(new AppleFactory());
Fruit fruitBox1 = fruitBoxStore1.getFruitBox();
// 结果: 我是一盒苹果, 已经削皮切块, 定价8块8
fruitBox1.getFruitName();
FruitBoxStore fruitBoxStore2 = new FruitBoxStore(new OrangeFactory());
Fruit fruitBox2 = fruitBoxStore2.getFruitBox();
// 结果: 我是橘子果盘, 已经切好, 售价9块9
fruitBox2.getFruitName();
}
}
小结:
当新增一个产品时, 需增加一个水果类和一个水果工厂类, 不需要修改代码(复合开闭原则)
创建果盘流程交给FruitBoxStore统一处理
缺点, 每次扩展要新增两个类, 类可能会很多