一、静态工厂(简单,但是增加多一个对象时要修改代码)
工厂代码
public class StaFactory { private static StaFactory ourInstance = new StaFactory(); public static StaFactory getInstance() { return ourInstance; } private StaFactory() { } public Animal getAnimal(String annimal){ switch (annimal){ case ("cat"):return new Cat(); case ("dog"):return new Dog(); default:return null; } } }
客户端代码
public static void main(String[] args) { Animal dog = StaFactory.getInstance().getAnimal("dog"); dog.run(); Animal cat = StaFactory.getInstance().getAnimal("cat"); cat.run(); }
二、普通工厂(增加对象时不用修改代码,但是要增加很多class文件)
只贴一个工厂的例子
public class DogFactory { private static DogFactory ourInstance = new DogFactory(); public static DogFactory getInstance() { return ourInstance; } private DogFactory() { } public Animal Create(){ return new Dog(); } }
客户端使用
//普通工厂 public static void main(String[] args) { Animal dog = DogFactory.getInstance().Create(); dog.run(); Animal cat = CatFactory.getInstance().Create(); cat.run(); }
三、抽象工厂,基本上是普通工厂的升级,只是多几个create方法
先写一个工厂接口
public interface AbFactory { Person createPerson(); Animal createAnimal(); }
再写一个工厂实例
public class HighFactory implements AbFactory { @Override public Person createPerson() { return new HighPerson(); } @Override public Animal createAnimal() { return new HighAnimal(); } }
客户端调用代码
//客户端调用代码 public static void main(String[] args) { HighFactory highFactory = new HighFactory(); highFactory.createAnimal().run(); highFactory.createPerson().say(); }