吃水果
我要吃水果应该怎么吃呢?
- 摘下自己想要吃的水果
- 清洗后,就可以吃了
//想吃的水果是苹果
public void eatFruit(){
Fruit fruit = new Apple();//得到一个苹果
fruit.wash();//水果被清洗
}
想吃香蕉呢?
public void eatFruit(){
Fruit fruit = new Banana();//得到一个香蕉
fruit.wash();//水果被清洗
}
发现了没,每次我想吃某种水果,我都要自己去找,自己去洗,我需要去关注怎么得到水果,怎么洗,果树如果枯萎了怎么办?果园关门了怎么办?可是我不关心这些,我只想要吃个水果而已。
那我们可以找一个专业的水果生产厂商提供水果
简单工厂模式(静态工厂模式)
- 把对象的创建和使用分开
- 将生产过程集中后,便于集中管理(增删改)
- 当水果类再有变动时,使用者不需要修改代码
此模式不属于23种设计模式,它只是工厂模式的基础
使用者只需要持有水果接口,再也不需要关心具体水果类
![](https://img.haomeiwen.com/i11851909/9bdb1e7e024cf1af.png)
public class FruitFactory{
/**
* 通过类型获得水果
*/
public Fruit getFruit(int type){
if(type == 1){
return new Apple();
} else if(type == 2){
return new Banana();
}
}
}
也可以使用多个方法
public class FruitFactory{
/**
* 得到苹果
*/
public Fruit getFruitApple(){
Fruit fruit = new Apple();
fruit.wash();
return fruit;
}
/**
* 得到香蕉
*/
public Fruit getFruitBanana(){
Fruit fruit = new Banana();
fruit.wash();
return fruit;
}
}
总结
简单工厂模式的目的是对获取对象的业务场景解耦
网友评论