设计模式(三) : 创建型模式--抽象工厂模式

抽象工厂模式适合于多于一个产品的产品族。

下面来看该模式的类图(《java与模式》):

示意性代码:

package com.javadesignpattern.abstractfactory;

public interface Creator {
    
    public ProductA factoryA();
    
    public ProductB factoryB();
    

}
package com.javadesignpattern.abstractfactory;

public interface ProductA {

}
package com.javadesignpattern.abstractfactory;

public interface ProductB {

}
package com.javadesignpattern.abstractfactory;

public class ConcreteCreator1 implements Creator {

    public ProductA factoryA() {
        // TODO Auto-generated method stub
        return new ConcreteProductA1();
    }

    public ProductB factoryB() {
        // TODO Auto-generated method stub
        return new ConcreteProductB1();
    }

}
package com.javadesignpattern.abstractfactory;

public class ConcreteCreator2 implements Creator {

    public ProductA factoryA() {
        // TODO Auto-generated method stub
        return new ConcreteProductA2();
    }

    public ProductB factoryB() {
        // TODO Auto-generated method stub
        return new ConcreteProductB2();
    }

}
package com.javadesignpattern.abstractfactory;

public class ConcreteProductA1 implements ProductA{

}
package com.javadesignpattern.abstractfactory;

public class ConcreteProductA2 implements ProductA{

}

  

package com.javadesignpattern.abstractfactory;

public class ConcreteProductB1 implements ProductB{

}

  

package com.javadesignpattern.abstractfactory;

public class ConcreteProductB2 implements ProductB {

}
package com.javadesignpattern.abstractfactory;

public class Client {
    
    public static void main(String[] args){
        Creator creator1 = new ConcreteCreator1();
        Creator creator2 = new ConcreteCreator2();
        
        creator1.factoryA();
        creator1.factoryB();
        
        creator2.factoryA();
        creator2.factoryB();
    }

}

 

我觉得抽象工厂和工厂方法的区别就在与抽象工厂创建的组合的产品。

  

posted @ 2014-05-29 16:47  Ruth/Christy  阅读(242)  评论(0编辑  收藏