Product:抽象产品角色,它定义了这个产品的通用属性,相当于模子,它定义了一些功能,这些功能可以由子类去实现

ConcreteProduct:具体产品角色,它实现了抽象产品所定义的功能,每个 ConcreteProduct 相当于一个产品种类

Factory:抽象工厂,它定义了所有工厂都应该具有的功能

ConcreteFactory:具体工厂模式类,它实现了抽象工厂定义的所有功能,负责创建具体的产品,它根据这个工厂的具体实现来生产具体的产品,但是这个产品也都具有符合抽象产品类定义的功能

 

 

Client:

package design.pattern.factory;

public class Client {
    public static void main(String[] args) {
        Factory factory = new ConcreteFactory();
        try {
            System.out.println(factory.getProduct(ProductType.PA));
            System.out.println(factory.getProduct(ProductType.PB));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("NO SUCH PRODUCT");
        }
    }
}

 

Factory:

public interface Factory {
    public Product getProduct(ProductType product) throws Exception;
}

 

Product:

package design.pattern.factory;

public abstract class Product {
    protected String type;
    
    protected Product(String type) {
        this.type = type;
    }
    
    @Override
    public String toString() {
        return type;
    }
}

 

ConcreteFactory:

package design.pattern.factory;

public final class ConcreteFactory implements Factory {

    @Override
    public Product getProduct(ProductType product) throws Exception {
        switch (product) {
        case PA:
            return new ConcreteProductA("ConcreteProductA");
        case PB:
            return new ConcreteProductB("ConcreteProductB");
        case PC:
            return new ConcreteProductC("ConcreteProductC");
        default:
            throw new Exception();
        }
    }

}

 

ConcreteProductA:

package design.pattern.factory;

public final class ConcreteProductA extends Product {
    
    public ConcreteProductA(String type) {
        super(type);
    }
    
}

 

ConcreteProductB:

package design.pattern.factory;

public final class ConcreteProductB extends Product{
    public ConcreteProductB(String type) {
        super(type);
    }
}

 

ConcreProductC:

package design.pattern.factory;

public final class ConcreteProductC extends Product{
    public ConcreteProductC(String type) {
        super(type);
    }
}

 

ProductType:

package design.pattern.factory;

public enum ProductType {
    PA,PB,PC;
}

 

posted on 2017-10-21 10:43  啊哈咧  阅读(152)  评论(0编辑  收藏  举报