正在读core of java,工厂类一直没搞懂。感觉和静态方法相类似,但是不知道是怎么运用在实际中。
20190711: 读了设计模式,里面给出的解读是这样的
Define an interface for creating an object ,but let subclasses decide which class to instantiate. Factory Method lets a class instantiatioin to subclasses.
抽象的一种表现,创建一个接口引用,由子类决定创建哪个实现;
public abstract class Product{ public void method1(){ } public abstract void method2(); }
public class ConcreteProduct1 extends Product{ public void method2(){} } public class ConcreteProduct2 extends Product{ public void method2(){} }
public abstract class Creator{ public abstract <T extends Product> T createProduct(Class<T> c); }
public class ConcreteCreator extends Creator{ public <T extends Product>T createProduct(Class <T> c){ ...... return (T) product; } }
public class Client{ @Test public void testMethod(){ Creator creator = new ConcreteCreator(); Product product = creator.createProduct(ConcreteProduct1.class); } }