工厂方法模式

工厂方法接口:

package c.build_type_factory_method;

import a.build_type.Animal;

/**
 * 工厂方法模式:
 * 		工厂方法模式中抽象工厂类负责定义创建对象的
 * 		接口,具体对象的创建工作由继承抽象工厂的具
 * 		体类实现。
 * 优点:
 * 		客户端不需要在负责对象的创建,从而明确了各个
 * 		类的职责,如果有新的对象增加,只需要增加一个
 * 		类和具体的工厂类即可,不影响已有的代码,后期
 * 		维护容易,增强了系统的扩展性。
 * 	缺点:
 * 		需要额外的编写代码,增加了工作量。
 * @author 半步疯子
 *
 */
public interface AnimalFactory02 {
	public abstract Animal createAnimal();
}

工厂方法实现:

package c.build_type_factory_method;

import a.build_type.Animal;
import a.build_type.Dog;

public class DogFactory implements AnimalFactory02{

	@Override
	public Animal createAnimal() {
		return new Dog();
	}
	
}
package c.build_type_factory_method;

import a.build_type.Animal;
import a.build_type.Cat;

public class CatFactory implements AnimalFactory02{

	@Override
	public Animal createAnimal() {
		return new Cat();
	}

}

工厂方法测试:

package c.build_type_factory_method;

import a.build_type.Animal;

public class AnimalTest02 {
	public static void main(String[] args) {
		// 需要狗
		AnimalFactory02 f01 = new DogFactory();	
		Animal d = f01.createAnimal();
		d.eat();
		
		// 需要猫
		AnimalFactory02 f02 = new CatFactory();
		Animal c = f02.createAnimal();
		c.eat();
	}
}



posted @ 2018-05-19 09:11  五彩世界  阅读(73)  评论(0编辑  收藏  举报