1.要什么实例就造什么对象(对象接收)
public class Cat { //生产 public void get() { System.out.println("生产一只猫"); } } public class Dog { //生产 public void get() { System.out.println("生产一条狗"); } } public class MainClass { public static void main(String[] args) { //实例对象 Dog dog = new Dog(); Cat cat = new Cat(); dog.get(); cat.get(); } }
2.要什么实例就造什么对象(接口父类接收)
public interface Animal { //生产动物 public void get(); } public class Dog implements Animal{ //生产 public void get() { System.out.println("生产一条狗"); } } public class Cat implements Animal { //生产 public void get() { System.out.println("生产一只猫"); } } public class MainClass { public static void main(String[] args) { /* //实例对象 Dog dog = new Dog(); Cat cat = new Cat(); dog.get(); cat.get();*/ Animal dog = new Dog(); Animal cat = new Cat(); dog.get(); cat.get(); } }
3.要什么实例就造什么对象(接口父类接收,工厂造)
public class AnimalFactory { public static Animal getDog() { return new Dog(); } public static Animal getCat() { return new Cat(); } } public class MainClass { public static void main(String[] args) { /* //实例对象 Dog dog = new Dog(); Cat cat = new Cat(); dog.get(); cat.get();*/ /* Animal dog = new Dog(); Animal cat = new Cat(); dog.get(); cat.get();*/ Animal dog = AnimalFactory.getDog(); dog.get(); AnimalFactory.getCat().get(); } }
4.要什么实例就造什么对象(接口父类接收,工厂造,提供参数)
public class AnimalFactory { /* public static Animal getDog() { return new Dog(); } public static Animal getCat() { return new Cat(); }*/ public static Animal getAnimal(String type) throws IllegalAccessException, InstantiationException { if ("dog".equalsIgnoreCase(type)) { return Dog.class.newInstance(); } else if ("cat".equalsIgnoreCase(type)) { return Cat.class.newInstance(); } else { System.out.println("目前工厂还造不出来"); return null; } } } public class MainClass { public static void main(String[] args) throws InstantiationException, IllegalAccessException { /* //实例对象 Dog dog = new Dog(); Cat cat = new Cat(); dog.get(); cat.get();*/ /* Animal dog = new Dog(); Animal cat = new Cat(); dog.get(); cat.get();*/ /* Animal dog = AnimalFactory.getDog(); dog.get(); AnimalFactory.getCat().get();*/ Animal dog = AnimalFactory.getAnimal("dog"); dog.get(); } }
5.要什么实例就造什么对象(接口父类接收,工厂造,提供参数,需要传递全类名)
public static Animal getAnimal(String type) throws IllegalAccessException, InstantiationException, ClassNotFoundException { /*if ("dog".equalsIgnoreCase(type)) { return Dog.class.newInstance(); } else if ("cat".equalsIgnoreCase(type)) { return Cat.class.newInstance(); } else { System.out.println("目前工厂还造不出来"); return null; }*/ Class animal = Class.forName(type); return (Animal) animal.newInstance(); } Animal dog = AnimalFactory.getAnimal("com.zs.Dog"); dog.get();
小结:简单工厂模式就注意三种角色,工厂类,父类(接口),子类(实现类);使用形式也比较通俗易懂,充分利用了面向对象的多态性,在java操作数据库的接口中就暴露了jdbc统一接口,
好处就是造能造出来的对象很容易,缺点就是造一个不存在的对象需要添加子类,修改接口,修改工厂类实例方法,耦合性很有点高,有模板才能造,麻烦在于造模板,严重违反开闭原则。