javascript 简单的工厂创作设计模式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 简单的工厂创作设计模式相关的知识,希望对你有一定的参考价值。

## Real world example
Consider, you are building a house and you need doors. It would be a mess if every time you need a door, you put on your carpenter clothes and start making a door in your house. Instead you get it made from a factory.

## In plain words
Simple factory simply generates an instance for client without exposing any instantiation logic to the client

## Wikipedia says
In object-oriented programming (OOP), a factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be "new".

## When to Use?
When creating an object is not just a few assignments and involves some logic, it makes sense to put it in a dedicated factory instead of repeating the same code everywhere.
/*
Door

getWidth()
getHeight()

*/

class WoodenDoor {
  constructor(width, height){
    this.width = width
    this.height = height
  }

  getWidth(){
    return this.width
  }

  getHeight(){
    return this.height
  }
}

const DoorFactory = {
  makeDoor : (width, height) => new WoodenDoor(width, height)
}

const door = DoorFactory.makeDoor(100, 200)
console.log('Width:', door.getWidth())
console.log('Height:', door.getHeight())

以上是关于javascript 简单的工厂创作设计模式的主要内容,如果未能解决你的问题,请参考以下文章

javascript设计模式-工厂模式(简单工厂)

使用javascript完成一个简单工厂设计模式。

JavaScript设计模式--简单工厂模式

创建型设计模式-简单工厂方法设计模式

JavaScript设计模式创建型设计模式--简单工厂工厂方法抽象工厂

JavaScript设计模式--简单工厂模式例子---XHR工厂