简体   繁体   English

工厂方法设计模式 Typescript

[英]Factory method design pattern Typescript

im just learning design pattern and i do not know whats the benefit of abstraction in below code: i rewrite the code and still work the way we want.我刚刚学习设计模式,我不知道在下面的代码中抽象有什么好处:我重写了代码,仍然按照我们想要的方式工作。

you can see the original code from here你可以从这里看到原始代码

class Creator {
  public factoryMethod() {}

  public someOperation(): string {
    const product = this.factoryMethod();
    return `Creator: The same creator's code has just worked with ${product}`;
  }
}

class ConcreteCreator1 extends Creator {
  public factoryMethod(): string {
    return '{Result of the ConcreteProduct1}';
  }
}

class ConcreteCreator2 extends Creator {
  public factoryMethod(): string {
    return '{Result of the ConcreteProduct2}';
  }
}

function clientCode(creator: Creator) {
  console.log(
    "Client: I'm not aware of the creator's class, but it still works."
  );
  console.log(creator.someOperation());
}

console.log('App: Launched with the ConcreteCreator1.');
clientCode(new ConcreteCreator1());
console.log('');

console.log('App: Launched with the ConcreteCreator2.');
clientCode(new ConcreteCreator2());

Comparing your code to the original, you have changed the abstract class Creator into a concrete class Creator .将您的代码与原始代码进行比较,您已将abstract class Creator更改为具体的class Creator This means that you can now instantiate this class by calling new Creator() .这意味着您现在可以通过调用new Creator()来实例化这个 class 。

The problem is that your base Creator class hasn't really implemented the factoryMethod() method.问题是您的基础Creator class 并没有真正实现factoryMethod()方法。 You have made it into a concrete method that does nothing and returns void .你已经把它变成了一个什么都不做并返回void的具体方法。 When you call clientCode(new Creator());当您调用clientCode(new Creator()); you get an output which is not what you want:你得到一个 output 这不是你想要的:

"Creator: The same creator's code has just worked with undefined" “创作者:同一创作者的代码刚刚使用未定义”

Why We Use Abstract Classes为什么我们使用抽象类

abstract class Creator {
    public abstract factoryMethod(): Product;
/* ... */

The original code example uses the abstract class Creator to establish the contract which all concrete creators must fulfill.原始代码示例使用abstract class Creator来建立所有具体创建者必须履行的合约。 It says: "in order to be a Creator , you must have a factoryMethod that returns a Product " .它说: “为了成为Creator ,你必须有一个返回ProductfactoryMethod

All concrete classes which extend Creator must implement the factoryMethod method.所有extend Creator的具体类都必须实现factoryMethod方法。 But the base abstract class Creator does not need to implement it.但是基础abstract class Creator不需要实现它。

The missing implementation is not a problem because an abstract class cannot be instantiated.缺少实现不是问题,因为抽象 class 无法实例化。 So it's not possible to have a Creator instance which lacks a factoryMethod .所以不可能有一个缺少factoryMethod的 Creator 实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM