设计模式-抽象工厂模式

抽象工厂模式

抽象工厂模式是能方便的创建一系列相关对象,而无需关心其具体类,客户端只需调用不同类别的工厂函数即可创建不同类别的一系列产品,比如:

  • 桌子+椅子
  • 汽车+方向盘等等

强调一系列,需要区别于工厂模式:父类提供创建对象接口,由子类决定创建对象类型

例子

假设有工厂需要生产桌子和椅子,有欧式风格和中式风格两种,并且中式风格和欧式风格不能混入,并且在不久的将来可能还会出现其他风格的产品。该例子我们就可以使用抽象工厂模式设计,通过不同的工厂生产不同风格的产品。

// 声明工厂函数,均需要生产椅子和桌子
interface AbstractFactory{
  createChair():AbstractChair;
  createTable():AbstractTable;
  
}
// 中国工厂
class ChinaFactory implements AbstractFactory {

  public createChair():AbstractChair {
    return new ChinaChair();
  }
  public createTable():AbstractTable {
    return new ChinaTable();
  }
}
// 欧洲工厂
class EuropeFactory implements AbstractFactory{

  public createChair():AbstractChair {
    return new EuropeChair();
  }
  public createTable():AbstractTable {
    return new EuropeTable();
  }
}
interface AbstractChair{
  useChair():string;
}
interface AbstractTable{
  useTable():string;
}
class EuropeChair implements AbstractChair{
  public useChair():string{
    return '这是欧洲椅子';
  }
}
class EuropeTable implements AbstractTable{
  public useTable():string{
    return '这是欧洲桌子';
  }
}

class ChinaChair implements AbstractChair{
  public useChair():string{
    return '这是中国椅子';
  }
}

class ChinaTable implements AbstractTable{
  public useTable():string{
    return '这是中国桌子';
  }
}


function client(factory:AbstractFactory){
  const chair:AbstractChair = factory.createChair();
  const table:AbstractTable = factory.createTable();

  console.log(chair.useChair());
  console.log(table.useTable());
}
// 中国工厂生产
client(new ChinaFactory());
console.log('-------')
// 欧洲工厂生产
client(new EuropeFactory());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值