Factory Method:定义一个用于创建对象的接口,让子类决定将哪一个类实例化。Factory Method使一个类的实例化延迟到其子类。
step1: define a abstract class , for example Windows;
step2:define subclasses of the abstract class, for example BigWindows, SmallWindows
step3:define a method in the factory class which returns a Window instance
code:
step1
public abstract class Window {
public abstract void func();
}
step2
public class WindowBig extends Window {
public void func() {
System.out.println("This is Big Window !");
}
}
public class WindowSmall extends Window {
public void func() {
System.out.println("This is Small Window !");
}
}
step3
public class Factory {
public Window CreateWindow (String type) {
if(type.equals("Big")) {
return new WindowBig();
} else if(type.equals("Small")) {
return new WindowSmall();
} else {
return new WindowBig();
}
}
// The Main function only for our test
public static void main(String[] args) {
Factory myFactory = new Factory();
Window myBigWindow = myFactory.CreateWindow("Big");
myBigWindow.func();
Window mySmallWindow = myFactory.CreateWindow("Small");
mySmallWindow.func();
}
}