• 初探工厂抽象模式


    设计模式的-工厂模式

    工厂模式之抽象类

    1.定义一个约定的规则抽象类   

    1. class ETFactory {
    2.      createStore() {
    3.          throw new Error('抽象方法,不允许直接调用,需重写')
    4. }
    5.      createUser(){
    6.           throw new Error('抽象方法,不允许直接调用,需重写')
    7.      }
    8. }

    案例:定义两个具体店铺

    定义一个地址的抽象规则类 

    1. class ETStore {
    2.       getAddress() {
    3.          throw new Error('抽象方法,需要重写')
    4.       }
    5. }

    继承上面地址的抽象类,创建方法

    万达具体实现类

    1. class WandaStore extends ETStore{
    2. getAddress(){
    3. return console.log('万达金铺360号')
    4. }
    5. }

    万象城具体实现类       

    1. class WanxiangchengStore extends ETStore{
    2.        getAddress(){
    3.            return console.log('万象城1006号一层')
    4.        }
    5. }


    定义:员工的抽象类     

    1. class ETUser {
    2.         getSkill(){
    3.           throw new Error('抽象方法,需要重写')
    4.         }
    5. }

    继承上面员工的抽象类,创建方法

    spa技师具体实现类       

    1. class SpaTech extends ETUser{
    2.       getSkill(){
    3.        return console.log('spa 技师:精油spa,香薰spa')
    4.       }
    5. }

    按摩技师具体实现类 

    1. class SofaTech extends ETUser{
    2.       getSkill(){
    3.         return console.log('按摩 技师:柔式按摩,瑜伽按摩')
    4.       }
    5. }

      定义一个具体的规则类     

    1. class AchieveFactory extends ETFactory {
    2.       createStore(){
    3.           return new WandaStore()
    4.       }
    5.       createUser(){
    6.          return new SpaTech()
    7.       }
    8. }

    创建一个店铺:

    1. // 开店喽
    2. const Honghong = new AchieveFactory()
    3. const store1 = Honghong.createStore()
    4. const store2 = Honghong.createUser()
    5. // 打印门店地址
    6. store1.getAddress()
    7. // 打印员工技能
    8. store2.getSkill()

    再创建一个新的店铺

    还是用之前创建的方法

    1. // 开新店喽
    2. // 定义一个具体的规则类
    3. class NewAchieveFactory extends ETFactory {
    4. createStore(){
    5. return new WanxiangchengStore()
    6. }
    7. createUser(){
    8. return new SofaTech()
    9. }
    10. }

    声明新的实例 

    1. // 开分店喽
    2. const Honghong1 = new NewAchieveFactory()
    3. const store3 = Honghong1.createStore()
    4. const store4 = Honghong1.createUser()
    5. // 打印门店地址
    6. store3.getAddress()
    7. // 打印员工技能
    8. store4.getSkill()

    下面是全部代码

    参考资料:

    JS设计模式_03工厂模式·抽象工厂 - 哔哩哔哩

  • 相关阅读:
    Elastic Stack 8.11:引入一种新的强大查询语言 ES|QL
    PostgreSQL的约束
    java毕业设计藏宝阁游戏交易系统Mybatis+系统+数据库+调试部署
    java版直播商城免费搭建平台规划及常见的营销模式+电商源码+小程序+三级分销+二次开发
    蜜罐技术是什么?为什么黑客最怕踩到蜜罐?
    boltdb 原理
    Go语言---动态查询数据库
    Vue2 修改了数组哪些方法,为什么
    06-添加用户关注、我的关注列表
    ENSP配置VXLAN实现相同网段用户通信(带抓包解析)
  • 原文地址:https://blog.csdn.net/weixin_42400404/article/details/139749000