js design pattern factory pattern

Keywords: Javascript

1. Simple factory mode, also known as static factory method, is a single type of replication

//Simple factory functions encapsulate animals

  function A(name, six) {
    var o = new Object()
     o.name = name
      o.six = six
      o.sayName = function () {
        return o
    var A1 = new A('Elephant', 'common')
    var A2 = new A('Lion', 'mother')
    A1.sayName()   // Elephant
    A2.sayName()   // Lion

2. Factory method, I understand that under similar products, a large factory can be defined, and many small factories can be inserted to realize the method. Small factories can be well coupled

/// / factory method

  var a = [{
    name: 'Duck',
      type: 'Graze'
       name: 'chicken',
    type: 'eat meat'

function B(type,chi) {


 B.prototype = {
  duck: function () {

     chicken: function (type) {
        this.type = type
 for(var i =0;i<a.length;i++){

3. Abstract factories, factories that can produce product families, such as nature (large factories), invertebrates, vertebrates, mammals (small factories), which can be divided into many kinds of animals (names, etc.) under the small factories. There are different survival rules among them, including those that eat grass and those that eat meat... Just like the following, each small factory has its own way to do its own things without interfering with each other. If it's OK, I can also inherit the meat eating animals and eat grass. It's also possible. Make a joke!! ()

//Make an abstract animal species

   var zoom= function (fun,fun2) {
         function c() {}
         c.prototype = new zoom[fun2]() // Create examples
         fun.constructor =fun //Constructor pointing
         // c function gives subclass prototype
         fun.prototype = new c()  
    zoom.Invertebrates = function () {
        this.type = 'Invertebrates'
    zoom.Invertebrates.prototype = {
          getzoom: function () {
              return new Error('Abstract method cannot be called!');
    // kingdom protista 
   var native = function (name,num) {
        this.name = name
        this.num = num
    native.prototype.getzoom = function(){
    var native1 = new native('Jellyfish', 20000000000)

Posted by ccjob2 on Mon, 02 Dec 2019 10:55:54 -0800