The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Class Diagram
public abstract class Product {
public void method1() {
//doSomething
}
public abstract void method2() ;
}
ConcreteProduct Role
public ConcreteProduct1 extend Product {
public void method2() {
//doSomething
}
}
public ConcreteProduct2 extend Product {
public void method2() {
//doSomething
}
}
Creator Role
public abstract class Creator {
public abstract <T extends Product> T createProduct(Class<T> c);
}
ConcreteCreator Role
public class ConcreteCreator extends Creator {
public <T extends Product> T createProduct(Class<T> c) {
Product product=null;
try {
product = (Product)Class.forName(c.getName()).newInstance();
} catch (Exception e) {
//error process
}
Return (T)product;
}
}
Client Role
public class Client {
public static void main(String[] args) {
Creator creator = new ConcreteCreator();
Product product = creator.creatorProduct(ConcreteProduct1.class);
//doSomething
}
}
沒有留言:
張貼留言