设计模式之简单工厂模式
设计模式之简单工厂模式
方案:主要通过向工厂中传入不同的参数,工厂将返回相应的类的实例,用户无需了解实例是怎样创建的,但是,向工厂中传入的参数是确定的,也就是说工厂所能创建的类的实例是需要事先知道的,当需要添加一个新类的时候,需要新写一个类,修改factory的逻辑判断,同时也修改客服端。
适用于创建少量对象的工厂
参考代码如下
/** * */package com.design.simpleFactory;/** * @author Lei * 动物类 */public abstract class AnimalObj {private String animalName;public AnimalObj(String name){this.animalName=name;} /** *动物运动行为 */public abstract void move();public String getAnimalName() {return animalName;}public void setAnimalName(String animalName) {this.animalName = animalName;}}
package com.design.simpleFactory;/** * @author Lei * 鸟类 */public class Bird extends AnimalObj {public Bird(String name) {super(name);}/** * 鸟飞 * */@Overridepublic void move() {System.out.println("bird fly");}}
/** * */package com.design.simpleFactory;/** * @author Lei * 人类 */public class People extends AnimalObj {public People(String name) {super(name);}/** * 人走 * */@Overridepublic void move() {System.out.println("people walk");}}
/** * */package com.design.simpleFactory;/** * @author Lei * 动物简单工厂 */public class AnimalFactory {public static AnimalObj createAnimal(int animal) {AnimalObj ani=null;switch (animal) {case 1:ani = new Bird("bird");break;case 2:ani = new People("people");break;}return ani;}}
/** * */package com.design.simpleFactory;/** * @author Lei * 测试类 */public class Test {public static void main(String args[]){AnimalObj bird=AnimalFactory.createAnimal(1);AnimalObj people=AnimalFactory.createAnimal(2);bird.move();people.move();}}