Portfolio model

  • What is composite mode
  • Combination patterns in life
  • The practical application of combination mode
  • Why use JS inheritance

Js inheritance literature

Official: Composite pattern, which combines objects into a tree structure to represent a partial-whole hierarchy, makes the use of individual objects and composite objects consistent. The key to mastering the composite pattern is to understand the meaning of “part/whole” as well as “single object” and “composite object”.

  • Okay, you can ignore the crap I said above and listen to my BB.

The namers of the legendary 23 design patterns have already given you a rough idea of what this is, but what we’re going to talk about is not just understanding it, but looking for opportunities to use it.

Combination patterns in life

There are many combination modes in life: McDonald’s package, Restaurant Meituan X-person package, Unicom data package, etc. They combine multiple ‘individuals’ into a’ whole ‘. This is an example in life. Let me use a recent practical small project to speak.

Here’s an example:

Recently, github created a little module called the gantt chart, which basically looks like this:

But how can the company want such traditional things, it must be innovative!! Specific have what, tradition only have one line, boss: give me to add two, one anticipate, one actual, want to have mileStone (mileStone), add a total progress, add…. Yun Yun, confidence is full whether you were scared, I realized one personally, may use combination mode to be better nevertheless, we try to use combination mode simply below 😆.

First, we make sure we do a component is called Gantt (Kentucky Fried chicken), what components include: divided into groups that (package) : drawing package (including: the progress bar, background grid, content), formatting packages, plus some simple tools: for the longest time and date format, just give you a chestnut.

It will look something like this:

Github open source address

As a specification, I will refer to Gantt as the (store) widget as the (package) and the in-component prototype method as the (member).

  • First build an inheritor wheel ↓
// Create an inheritObject and inheritPrototype with Jquery ()function () {
    var util = {
        inheritObject: function(o) {// Object inheritance encapsulates var F =function() {}; F.prototype = o;return new F();
        },
        inheritPrototype: function(subClass, supperClass) {var obj = this.inheritObject(supperClass.prototype); obj.constructor = subclass; subclass.prototype = obj; }}; window.$ = window.util = util; })(window); // Put the closure variable into the global var Gantt =function (data) {
    this.ganttData = data;
    this.children = [];
    this.element = null;
}

Gantt.prototype = {
    init: function () {
        throw new Error('This method must be subclassed')
    },
    build: function () {
        throw new Error('This method must be subclassed'},} /** * create a Gantt outer Container * @param name * @param parent * @constructor */ var Container =function(name, parent) { Gantt.call(this); this.name = name; this.parent = parent; this.init(); } $.inheritPrototype(Container, Gantt); // Container. Prototype = {/** *function () {
        this.element = document.createElement('div'); // Create a div element this.element.name = this.name; this.element.id ='ganttView'; this.parent.append(this.element); }, /** * overwrite the parent class build */ build:function(child, text) { child.append(document.createTextNode(text)); // Add the test description this.children.push(child); this.element.appendChild(child);return this;
    },
    getElement: function () {
        return this.element;
    },
    draw: function() {this.parent.appendChild(this.element)}}'GanttView', document.body);
ganttView.build(document.createElement("div"), 'Left Side Detail Item 1')
    .build(document.createElement("div"), 'Left Details Item 2').build(document.createElement("div"), 'Draw on the right'To save time CSS will not write,Copy the code
float:left; height,width, color,backbround, text:center..... Imagination... ` ` `Copy the code

Note that the Container is a secondary Container that is gradually drawn from the original ‘body’ element of a parent, with more complex content (calculating the maximum time range, drawing the background, adding a calendar, etc.)

There should also be descriptions, details, drawings, and so on in item and of course descriptions, details, and drawings are packages, and they still need the lowest level of members to be the foundation, and the members are the lowest level, they no longer have subclasses, but they inherit from their parent class.

So let’s change the code as a whole:

  var Gantt = function (data) {
        this.ganttData = data;
        this.children = [];
        this.element = null;
    }

    Gantt.prototype = {
        init: function () {
            throw new Error('This method must be subclassed')
        },
        build: function () {
            throw new Error('This method must be subclassed'},} /** * create a Gantt outer Container * @param name * @param parent * @constructor */ var Container =function(name, parent) { Gantt.call(this); this.name = name; this.parent = parent; this.init(); } $.inheritPrototype(Container, Gantt); // Container. Prototype = {/** *function () {
            this.element = document.createElement('div'); // Create a div element this.element.id ='ganttView'; this.element.textContent= this.name; this.parent.append(this.element); }, /** * overwrite the parent class build */ build:function(child) { // child.append(document.createTextNode(text)); // Add the test description this.children.push(child); this.element.appendChild(child.element);return this;
        },
        getElement: function () {
            return this.element;
        },
        draw: function() {this.parent. AppendChild (this.element)}} /** * create a basic member of Gantt * @param name * @param parent * @constructor */ var Item =function(name, parent) { Gantt.call(this); this.name = name; this.parent = parent; this.init(); } $.inheritPrototype(Item, Container); // item. prototype = {/** */function () {
            this.element = document.createElement('div'); // Create a div element this.element.id ='ganttItem';
            this.element.textContent = this.name;
//            this.parent.append(this.element);
//            returnthis.element; }, /** * overwrite the parent class build */ build:function(text) {// Redraw the progress bar and bind the click event to the progress bar}, getElement:function () {
            return this.element;
        },
        draw: function() {this.parent.appendChild(this.element)}}'GanttView', document.body);
        container.build(new Item('Left Side Detail Item 1'))
                .build(new Item('Left Details Item 2')) ` ` `! [](https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2017/10/18/997cfd2b701a539045c4dad52aa460f3~tplv-t2oag A2asx -image.image) - Can't I just 'new'? "Yes, but remember, we use the combination mode shall safeguard the unity of the interface, which is [object-oriented programming] (https://juejin.cn/post/6844903475843694600), similar ` Java ` ` interface ` interface, This makes it easier to handle callbacks, exceptions, simplify the complex whole, and enrich the whole with subclasses. "I used to write the gantt chart, generated in one time, if the product is put forward, if use ` long round robin ` listening to the server, if the server adds a task, in the form of animation dynamically add a progress bar, it changes for my old component is bigger, but this is very simple, can we add an add method of prototype inheritance. - What are the benefits of combo mode? "Making projects more modular, where a component can be broken down into packages indefinitely until it reaches the lowest member, writing code at an atomic level, is very good for code maintenance." Open source [Gantt plugins] (https://github.com/pkwenda/gantt.js) is based on ` Jquery ` extensions, did not use the heavy components such as SVG, only rely on Jquery, only 14 k, there are some bright spots not submitted, then the comparison of writing in a hurry, Now that I think about it more recently, it might be more appropriate to consider a composite pattern at that time for later changes in requirements. Greatly saving development time.### Finally, I hope you can write more sexy code
 
Copy the code