官术网_书友最值得收藏!

Chapter 3. Creational Patterns

In the last chapter, we took a long look at how to fashion a class. In this chapter, we'll look at how to create instances of classes. On the surface it seems like a simple concern, but how we create instances of a class can be of great importance.

We take great pains in creating our code such that it can be as decoupled as much aspossible. Ensuring that classes have minimal dependence on other classes is the key to building a system that can change fluently with the changing needs of those using the software. Allowing classes to be too closely related means that changes ripple through them.

One ripple isn't a huge problem but as you throw more and more changes into the mix, the ripples add up and create interference patterns. Soon the once placid surface is an unrecognizable mess of additive and destructive nodes. This problem also occurs in our applications: the changes magnify and interact in unexpected ways. One situation in which we tend to forget about coupling is when creating objects as can be seen in the following code:

var Westeros;
(function (Westeros) {
  var Ruler = (function () {
    function Ruler() {
      this.house = new Westeros.Houses.Targaryen();
    }
    return Ruler;
  })();
  Westeros.Ruler = Ruler;
})(Westeros || (Westeros = {}));

You can see in this class that the Ruler variable's house is strongly coupled to the Targaryen class. If this were ever to change, then this tight coupling would have to change in a great number of places. This chapter discusses a number of patterns, which were originally presented in the Gang of Four book, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley. The goal of these patterns is to improve the degree of coupling in applications and increase the opportunities for code reuse.

The patterns are as follows:

  • Abstract Factory
  • Builder
  • Factory Method
  • Singleton
  • Prototype

Of course not all of these are applicable to JavaScript, but we'll see all about that as we work through the creational patterns.

主站蜘蛛池模板: 余江县| 望江县| 星座| 乐山市| 闸北区| 胶州市| 远安县| 平罗县| 天水市| 洛隆县| 安远县| 仁怀市| 青岛市| 漳州市| 平阴县| 西宁市| 桐梓县| 邛崃市| 集安市| 祁东县| 莆田市| 黑水县| 元谋县| 从化市| 泽州县| 木兰县| 黄平县| 杭州市| 景宁| 诸城市| 建始县| 名山县| 满洲里市| 五台县| 芷江| 晋城| 随州市| 永平县| 玉环县| 正宁县| 仲巴县|