工厂方法和抽象工厂——Factory Method & Abstract Factory

一、使用抽象工厂和工厂方法

Factory Method Pattern工厂方法  和  Abstract Factory Pattern抽象工厂  是两种不同的设计模式。《Java设计模式》书上给出了如下定义,但是Sam觉得有点问题,在网上找了找资料,在后文将给出我自己的理解。

 

Factory Method Pattern   P167

    The intent of Factory Method is to let a class developer define the interface(统一接口) for creating an object while retaining control of which class to instantiate(使用具有统一接口的类中的某一个).

 

Abstract Factory Pattern   P175

    Sometimes, you want to provide for object creation while still retaining control of which class to instantiate. In such circumstances, you can apply the Factory Method pattern with a method that uses an Outsider Factor to determine which class to instantiate. Sometimes, the factor that controls which object to instantiate can be thematic, running across several classes.

    The intent of Abstract Factory, or KIT, is to allow the creation of families of related or dependent objects.

 

调用:

public static void main(String[] args) {
        Fruit f = Factory.getInstance("apple");
        if(f!=null) f.eat();
       
        Fruit f1 = Factory.getInstance("orange");
        if(f1!=null) f1.eat();
       
        Fruit f2 = Factory.getInstance("");
        if(f2!=null) f2.eat();

}

 

定义工厂类:

class Factory{    // 定义工厂类
    public static Fruit getInstance(String className){
        Fruit f = null ;
        if("apple".equals(className)){    // 判断是否要的是苹果的子类
            f = new Apple() ;
        }
        if("orange".equals(className)){    // 判断是否要的是橘子的子类
            f = new Orange() ;
        }
        return f ;
    }
};

定义产品类:

interface Fruit{    // 定义一个水果接口
    public void eat() ;    // 吃水果
}
class Apple implements Fruit{
    public void eat(){
        System.out.println("** 吃苹果。") ;
    }
};
class Orange implements Fruit{
    public void eat(){
        System.out.println("** 吃橘子。") ;
    }
};

 

 

如何记忆——“抽象工厂”和“工厂方法”的核心思想是:

       (1) 所有的“具体工厂”都可以定义统一的“抽象工厂”父类/父接口;——上例中略去了“抽象工厂”的定义

       (2) 所有的“具体产品”都可以定义统一的“抽象产品”父类/父接口;

       (3) 通过(具体)工厂返回“抽象产品”实例,但实际上在内部采用“具体产品”的构造方法构造。

 

       这样一来,用户使用时只接触到“抽象工厂”和“抽象产品”,不涉及具体构造工作。

 

二、 抽象工厂和工厂方法的区别

 

工厂方法模式
一个抽象产品类,可以派生出多个具体产品类。  
一个抽象工厂类,可以派生出多个具体工厂类。  
每个具体工厂类只能创建一个具体产品类的实例。




抽象工厂模式
多个抽象产品类,每个抽象产品类可以派生出多个具体产品类。  
一个抽象工厂类,可以派生出多个具体工厂类。  
每个具体工厂类可以创建多个具体产品类的实例。  

 

区别
工厂方法模式只有一个抽象产品类,而抽象工厂模式有多个。  
工厂方法模式的具体工厂类只能创建一个具体产品类的实例,而抽象工厂模式可以创建多个。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值