java设计模式之简单工厂模式(创建型模式)

/**
 * ## 具体产品(Concrete Product)角色
 *
 */
public class Apple implements Fruit {

	public void grow() {
		System.out.println("Apple is growing--------------");
	}

	public void plant() {
		System.out.println("Apple is planting--------------");
	}

	public void harvest() {
		System.out.println("Apple is harvesting--------------");
	}

}


package com.createtype.desginpatterns.facotry.simplefactory;

public interface Fruit {
	public void grow();

	public void plant();

	public void harvest();
}

package com.createtype.desginpatterns.facotry.simplefactory;
/**
 * ## 简单工厂(Creator)角色
 * 
 */
public class Gardener {

	public static Fruit factory(String fruit){
		if (fruit.equalsIgnoreCase("apple")) {
			return new Apple();
		} else if (fruit.equalsIgnoreCase("grape")) {
			return new Grape();
		} else {
			return null;
		}
	}
}
 

package com.createtype.desginpatterns.facotry.simplefactory;
/**
 * ## 具体产品(Concrete Product)角色
 *
 */
public class Grape implements Fruit {

	public void grow() {
		System.out.println("Grape is growing--------------");
	}

	public void plant() {
		System.out.println("Grape is planting--------------");
	}

	public void harvest() {
		System.out.println("Grape is harvesting--------------");
	}
	
}
 

package com.createtype.desginpatterns.facotry.simplefactory;

public class Test {

	/**
	=> 简单工厂角色:核心,封装商业逻辑,通常由一个具体Java类实现
	=> 抽象产品角色:简单工厂模式创建的对象的父类或者共同的接口,通常由一个Java抽象类或者Java接口实现
	=> 具体产品角色:简单工厂模式创建的对象是该类的实例,通常由一个具体Java类实现
	=> 优点:
	              1. 模式核心是工厂类,该类含有必要的判断逻辑,可以决定在什么时候创建哪一个产品类实例.
	              2. 客户端避免了直接创建产品对象的责任,仅仅负责消费产品.实现责任分割.
	=> 缺点:
	               1. 工厂类为上帝类(God Class),一旦它受影响了,涉及整个系统正常运作
	               2. 工厂类中集中了过多的逻辑,难以维护及扩展
	               3. 新的产品类加入系统时,工厂角色需要做相应修改,不支持"开-闭"原则
	=> 应用: DateFormat.getInstance() -> 返回其子类实例对象,如SimpleDateFormat
	 */
	public static void main(String[] args) {

		
		
		
		
	}

}

猜你喜欢

转载自lvwenwen.iteye.com/blog/1546074