前端-工厂模式

工厂模式大体分为三类: 简单工厂模式工厂方法模式抽象工厂模式。三者之间的关系,也是渐进式的,抽象化的范围也是越来越高。

  • 简单工厂模式:根据不同条件去生成不同对象(当数据量多时,简单工厂模式显而易见的的不适用)
  • 工厂方法模式:归类对象,对同一类型的对象进行归整(作用与同一类产品)
  • 抽象工厂模式:不同类别的对象,进行层层递进

简单工厂模式

interface IPhone {
  name: string;
  price: number;
}


enum Phones {
  hw,
  mi
}

// 这里的 Shop 则表示一个工厂,它将数据包裹,根据需求提供数据。
class Shop {
  // 华为手机
  hwPhone:IPhone = {
    name: "mate 40",
    price: 4000,
  };
  
  // 小米手机
  miPhone:IPhone = {
    name: "p40",
    price: 4000,
  };

  getPhone(type: Phones): IPhone{
    switch (type) {
      case Phones.hw:
        return this.hwPhone;
      case Phones.mi:
        return this.miPhone;
    }
  }
}

const shop1 = new Shop();
const mi1 = shop1.getPhone(Phones.mi);
mi1.name = "nihao";

const shop2 = new Shop();
const mi2 = shop2.getPhone(Phones.mi);

console.log(mi1, mi2);

工厂方法模式

interface IPhone {
  name: string;
  price: number;
}
class Phone {
  name: string;
  price: number;

  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }
}

class Shop {
  getPhone(name: string, price: number): IPhone{
    // 通过 子类 去实现数据的创建
    return new Phone(name, price);
  }
}

const shop1 = new Shop();
const phone1 = shop1.getPhone("华为", 4500);

const shop2 = new Shop();
const phone2 = shop2.getPhone("小米", 4000);

console.log(phone1, phone2);

抽象工厂模式

// 手机的抽象类
abstract class Phone {
  name: string;
  price: number;

  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }

  abstract call(): void;
}

// 笔记本的抽象类
abstract class Laptop {
  name: string;
  price: number;

  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }

  // 打游戏
  abstract game(gameName: string): void;
}

/**
 * 小米本身作为一个产品簇,拥有手机,笔记本的多个品种,
 *  1. 先实现产品簇中的某个产品类;
 *  2. 在通过整个工厂,整合所有的产品
 */
class MiPhone extends Phone {
  call() {
    console.log("少林功夫好哎");
  }
}

class MiLaptop extends Laptop {
  game(gameName: string) {
    console.log(`小米电脑适合${gameName}`);
  }
}

class Mi {
  getPhone(name: string, price: number) {
    return new MiPhone(name, price);
  }

  getLaptop(name: string, price: number) {
    return new MiLaptop(name, price);
  }
}

class HuaweiPhone extends Phone {
  call() {
    console.log("少林功夫好哎");
  }
}

/**
 * 华为效果类似 
 * 
*/
class HuaweiLaptop extends Laptop {
  game(gameName: string) {
    console.log(`小米电脑适合${gameName}`);
  }
}

class Huawei {
  getPhone(name: string, price: number) {
    return new HuaweiPhone(name, price);
  }

  getLaptop(name: string, price: number) {
    return new HuaweiLaptop(name, price);
  }
}

const miShop = new Mi();
const miPhone = miShop.getLaptop("P40", 3600);
console.log(miPhone);

const huaweiShop = new Huawei();
const huaweiPhone = huaweiShop.getLaptop("meta 40", 4000);
console.log(huaweiPhone);
posted @ 2023-03-27 17:29  千年轮回  阅读(79)  评论(0编辑  收藏  举报