java设计模式——抽象工厂(AbstractFactory)

 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

 适用性

 
    1.一个系统要独立于它的产品的创建、组合和表示时。
 
    2.一个系统要由多个产品系列中的一个来配置时。
 
    3.当你要强调一系列相关的产品对象的设计以便进行联合使用时。
 
    4.当你提供一个产品类库,而只想显示它们的接口而不是实现时。
                       

 参与者

 
    1.AbstractFactory
      声明一个创建抽象产品对象的操作接口。
 
    2.ConcreteFactory
      实现创建具体产品对象的操作。
 
    3.AbstractProduct
      为一类产品对象声明一个接口。
 
    4.ConcreteProduct
      定义一个将被相应的具体工厂创建的产品*象。
      实现abstractProduct接口。
 
    5.Client
      仅使用由AbstractFactory和AbstractProduct类声明的接口
 
 

例子

abstractFactory

 
public interface IAnimalFactory {
 
    ICat createCat();
        
    IDog createDog();
}

 

ConcreteFactory

 
public class BlackAnimalFactory implements IAnimalFactory {
 
    public ICat createCat() {
        return new BlackCat();
    }
 
    public IDog createDog() {
        return new BlackDog();
    }
 
}
 
public class WhiteAnimalFactory implements IAnimalFactory {
 
    public ICat createCat() {
        return new WhiteCat();
    }
 
    public IDog createDog() {
        return new WhiteDog();
    }
 
}

AbstractProduct

 
public interface ICat {
 
    void eat();
}
 
public interface IDog {
 
    void eat();
}

Concreteproduct

 
public class BlackCat implements ICat {
 
    public void eat() {
        System.out.println("The black cat is eating!");
    }
}
public class WhiteCat implements ICat {
 
    public void eat() {
        System.out.println("The white cat is eating!*);
    }
 
}
 
public class BlackDog implements IDog {
 
    public void eat() {
        System.out.println("The black dog is eating");
    }
 
}
 
public class WhiteDog implements IDog {
 
    public void eat() {
        System.out.println("The white dog is eating!");
    }
 
}

Client

 
public static void main(String[] args) {
    IAnimalFactory blackAnimalFactory = new BlackAnimalFactory();
    ICat blackCat = blackAnimalFactory.createCat();
    blackCat.eat();
    IDog blackDog = blackAnimalFactory.createDog();
    blackDog.eat();
    
    IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory();
    ICat whiteCat = whiteAnimalFactory.createCat();
    whiteCat.eat();
    IDog whiteDog = whiteAnimalFactory.createDog();
    whiteDog.eat();
}

result

 
The black cat is eating!
The black dog is eating!
The white cat is eating!
The white dog is eating!

形象比喻:

ABSTRACT FACTORY—追MM少不了请吃饭了,麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西,虽然口味有所不同,但不管你带MM去麦当劳或肯德基,只管向服务员说“来四个鸡翅”就行了。麦当劳和肯德基就是生产鸡翅的Factory

工厂模式:客户类和工厂类分开。消费者任何时候需要某种产品,只需向工厂请求即可。消费者无须修改就可以接纳新产品。缺点是当产品修改时,工厂类也要做相应的修改。如:如何创建及如何向客户端提供。

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值