莉莉丝
2020-06-14 18:32:19
Java设计模式学习笔记——简单工厂模式
简单工厂模式的三个基本角色
- 静态工厂类: if 语句硬编码,破坏了开闭原则;不符合单一职责原则
- 抽象产品类:接口、抽象类
- 具体产品类:
Example
抽象产品类
/**
*
* @author yukyd
* Open for extension, Closed for modification
*
*/
public interface Fruit {
void plant();
void harvest();
}
|
具体产品类
/**
*
* @author yukyd
* 描述苹果相关信息,比如种苹果、摘苹果
*
*/
public class Apple implements Fruit {
public void plant() {
System.out.println("We are planting apples...And, the apples are growing...");
}
public void harvest() {
System.out.println("The apples are mature...");
System.out.println("The apples are ready to eat..."); //这英语语法有点鬼
}
}
public class Orange implements Fruit {
@Override
public void plant() {
// TODO Auto-generated method stub
System.out.println("We are planting oranges...And, the oranges are growing...");
}
@Override
public void harvest() {
// TODO Auto-generated method stub
System.out.println("The oranges are mature...");
}
}
工厂类
/**
*
* @author yukyd
* 负责产生苹果对象
* 记得研究static
*
*/
public class Farm {
// static Apple x; //创建后的对象(结果)
// static Apple createApple() {
// //对象的创建和使用相分离,创建的过程
// x = new Apple();
// return x;
//// return new Apple();
// }
//面向抽象
static Fruit x;
static Fruit createFruit(String request) {
//可改为 switch 语句
if(request.equals("apple")) {
x = new Apple();
} else if(request.equals("orange")) {
x = new Orange();
} else {
System.out.println("Sorry, we do not produce the fruit temporarily...");
}
return x;
}
}
客户端
/**
*
* @author yukyd
* 消费者类
*
*/
public class Consumer {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Apple myfruit = Farm.createApple();
//依据:依赖倒置原则,里氏替换原则
Fruit myfruit = Farm.createFruit("apple"); //Farm.createFruit(/*客户需求参数*/)
// Fruit myfruit = Farm.createFruit("pear"); //没有pear,抛出空指针异常
if(myfruit!=null) {
myfruit.plant();
myfruit.harvest();
}
// else System.out.println("No such fruit");
}
}
优缺点 Advantage
Defect
|
评论
最近浏览
刘先生-OL LV13
2022年11月21日
余不二 LV2
2022年1月4日
feel
2021年11月24日
暂无贡献等级
zhos0212 LV19
2021年9月22日
小于一直在 LV1
2021年7月1日
sn1907744721 LV1
2021年6月21日
512427918
2020年12月30日
暂无贡献等级
nilongjing LV2
2020年12月27日
mySong LV11
2020年10月13日
itxjvip LV2
2020年8月14日


