莉莉丝的gravatar头像
莉莉丝 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

  • 工厂类集中了所有产品的创建逻辑,职责过重,一旦不能正常工作,整个系统都要受到影响

  • 增加系统中类的个数(引入了新的工厂类),增加了系统的复杂度和理解难度

  • 系统扩展困难,一旦添加新产品不得不修改工厂逻辑

  • 仅对生产的结果进行封装,生产过程无封装

  • 工厂类中 if 嵌套过多,破坏了原有的封装,可读性差

  • 不符合 单一职责原则 SRP、开闭原则 OCP


打赏
最近浏览
刘先生-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日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友