具体实现
package com.designmode.factorymethod;
public abstract interface Product {}
package com.designmode.factorymethod;
public class ConcreteProduct implements Product{
public ConcreteProduct() {
System.out.println("i am ConcreteProduct");
}
}
package com.designmode.factorymethod;
public class ConcreteProduct1 implements Product{
public ConcreteProduct1() {
System.out.println("i am ConcreteProduct1");
}
}
package com.designmode.factorymethod;
public class ConcreteProduct2 implements Product{
public ConcreteProduct2() {
System.out.println("i am ConcreteProduct2");
}
}
package com.designmode.factorymethod;
public abstract class Factory {
abstract public Product factoryMethod();
public void dosomething() {
Product product = factoryMethod();
}
}
package com.designmode.factorymethod;
public class ConcreteFactory extends Factory{
@Override
public Product factoryMethod() {
System.out.println(" i am ConcreteFactory");
return new ConcreteProduct();
}
}
package com.designmode.factorymethod;
public class ConcreteFactory1 extends Factory{
@Override
public Product factoryMethod() {
System.out.println(" i am ConcreteFactory1");
return new ConcreteProduct1();
}
}
package com.designmode.factorymethod;
public class ConcreteFactory2 extends Factory{
@Override
public Product factoryMethod() {
System.out.println(" i am ConcreteFactory2");
return new ConcreteProduct2();
}
}
主函数
package com.designmode.factorymethod;
/**
* 工厂模式:提供一个创建对象的通用接口,但由子类决定实例化哪个类。
* Factory:工厂抽象类,生产产品。
* ConcreteFactory\ConcreteFactory1\ConcreteFactory2分别生产product、product1和product2。
* Client:生产不同的产品,让不同的子类实现就可以。
* @author HeXiaoli
*
*/
public class Client {
public static void main(String[] args) {
ConcreteFactory1 concreteFactory1 = new ConcreteFactory1();
concreteFactory1.dosomething();
}
}