Fork me on GitHub

工厂模式

工厂模式方法模式:

工厂方法模式中抽象工厂类负责定义创建对象的接口,

具体对象的创建工作由继承抽象工厂的具体类实现。

优点:

客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,

只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,

增强了系统的扩展性。

缺点:

需要额外的编写代码,增加了工作量

如下:一个造动物的工厂

1.动物接口
package shejimoshi.Factory;
//动物接口
public interface Animal {
 public abstract void eat();
}
2.动物工厂接口
package shejimoshi.Factory;
//动物工厂接口
public interface AnimalFactory {
   public abstract Animal creatAniaml();
}

 3.具体动物

package shejimoshi.Factory.impl;

import shejimoshi.Factory.Animal;
//具体动物猫
public class Cat implements Animal {


	public void eat() {
		System.out.println("猫吃鱼");
	}

}

  

package shejimoshi.Factory.impl;

import shejimoshi.Factory.Animal;
//具体动物狗
public class Dog implements Animal {

	public void eat() {
		System.out.print("狗吃肉");

	}

}

  4.具体动物工厂

package shejimoshi.Factory.impl;

import shejimoshi.Factory.Animal;
import shejimoshi.Factory.AnimalFactory;
//具体造猫厂
public class CatFactory implements AnimalFactory {

	
	public Animal creatAniaml() {
		
		return new Cat();
	}

}

  

package shejimoshi.Factory.impl;

import shejimoshi.Factory.Animal;
import shejimoshi.Factory.AnimalFactory;
//具体造狗厂
public class DogFactory implements AnimalFactory {

	
	public Animal creatAniaml() {
		
		return new Dog();
	}

}

  5.测试test

package shejimoshi.Factory;

import shejimoshi.Factory.impl.CatFactory;
import shejimoshi.Factory.impl.DogFactory;
//测试类
public class test {
public static void main(String[] args) {
	AnimalFactory dog=new DogFactory();
	dog.creatAniaml().eat();
	System.out.println();
	AnimalFactory cat=new CatFactory();
	cat.creatAniaml().eat();
}
}

  如果需要造新动物只需要在3,4步添加具体动物和对应的具体动物工厂即可。

posted @ 2018-08-30 16:44  雪人奥特曼  阅读(124)  评论(0编辑  收藏  举报