工厂模式(think in java中的设计模式)

工厂模式:工厂模式是利用工厂类的工厂方法创建对象的一种设计模式,目的是创建对象,但是很多时候创建对象我们会考虑很多其他因素~~~~比如在创建的过程中进行一些判断,通过不同的工厂模式就能把这些东西分离开来。

public class Test2 {
    @Test
    public void t() throws InstantiationException, IllegalAccessException, ClassNotFoundException {

        A a=(A) Factory.builder("A");
        System.out.println(a.name);
        B b=(B) Factory.builder("B");
        System.out.println(b.name);
    }
}
class Factory{
    static public  Object  builder(String typeName ) 
            throws InstantiationException, IllegalAccessException, ClassNotFoundException{
        
        Object o=null;
        if(typeName.equals("A")){
            o=new A();
        }else if(typeName.equals("B")){
            o=new B();
            }
        
        return o;
    }
}
class A {
    String name="168";
}

class B {
    String name="178";
}

蛋蛋的抽象工厂模式普通工厂模式~~~~~抱着实用主义的精神看懂了两种模式就好不要去介意两者有什么区别,用的时候能用上就好,纠结细节会让我们失去更多