"JS design mode" uses a singleton mode (Singleton) to encapsulate the addition and deletion of data.

Source: Internet
Author: User

Single-Case mode
The core structure of the singleton pattern contains only one special class that is called a singleton. The singleton mode ensures that there is only one instance of a class in the system.


The initial definition of the singleton pattern appears in design mode (Eddisonvis, 1994): "Guarantees that a class has only one instance, and provides a global access point to access it." ”


The singleton pattern defines: "A class has and has only one instance, and self-instantiation is provided to the system as a whole." ”
var Singleton = (function () {  singletonclass () {  }  var Singleton = null;  return {    getinstance:function () {      if (singleton = = null) {singleton = new Singletonclass ();      } else {return Si Ngleton;}}}  ) ();

Singleton.getintance ();

The front end often uses some and interface related additions and deletions to change the asynchronous operation. For example, when I manipulate data lists, I often have to add changes to the delete function. Some programs are synchronized (refresh the page), the user experience better asynchronous;


The code is as follows


Add Features
$ (". Add"). Click (function () {   $.ajax ({type: "POST"        DataType: "json",        URL: "http://www.csdn.net/",        Data: {name: "csdn blog", dir: "Web Front End"},        success:function (result) {    if (result.status) {alert ("New success! ")} else {  alert (" New Failed ")},        error:function () {    alert (" New async, add or contact technical Administrator ");});})   ;


Remove Features
$ (". Del"). Click (function () {   $.ajax ({type: "POST"        DataType: "json",        URL: "http://www.csdn.net/",        Data: {ID: ' 1 '},        success:function (result) {    if (result.status) {alert ("Delete succeeded! ")} else {  alert (" Delete Failed "}},        error:function () {    alert (" Add new async, add or contact technical Administrator ");});})   ;

The above two code snippets briefly describe the JS code for adding and removing functions. Some students found that they have in common, is the AJAX request is part of the same, and delete the function if it is used elsewhere? , then write the same code in other places. It feels uncomfortable.

Let's improve.
var Singletoncrud = (function () {Singletonclass () {} Singletonclass.prototype = {Constructor:singletonclass, a Dd:function (data) {$.ajax ({type: "POST" DataType: "json", url: "http://www.csdn.net/", data : Data, Success:function (result) {if (result.status) {alert ("added success!  ")} else {alert (" New Failed ")}}, Error:function () {alert (" New async, please add or contact technical Administrator ");     }       });          }, Remove:function (data) {$.ajax ({type: "POST" DataType: "json", url: "http://www.csdn.net/", Data:data, success:function (Result) {if (result.status) {alert ("Delete succeeded!  ")} else {alert (" Delete Failed "}}, Error:function () {alert (" New async, please add or contact technical Administrator ");     }       });  }} var singleton = null;      return {getinstance:function () {if (singleton = = null) {singleton = new singletonclass ();      } else {return singleton; }    }  }})();

var curd = singletoncrud.getintance ();

$ (". Add"). Click (function () {   var data = {"name": "Name"};   Curd.add (data);}); $ (". Del"). Click (function () {   var data = {"id": 1};   Curd.remove (data);});

Often use singleton examples to do some tool tools class;

Use design pattern Advantages: Decoupling, readability, code structure is clear;

From the small example above, the Access data in the Click event (click event function) and operation data (Ajax request) are separated;



Through the optimized code for the singleton pattern:

var Singletoncrud = (function () {  singletonclass () {}  Singletonclass.prototype = {     constructor: Singletonclass,     ajax:function (URL, data success) {$.ajax ({  type: "Post"          DataType: "JSON",          Url:url,          Data:data,          success:success,          error:function () {    alert ("Add new async, please add or contact technical Administrator");}       );     ,     add:function (data) {This.ajax ("http://www.csdn.net/", data, function (result) {    if (result.status) {Aler T ("added success! ")} else {  alert (" New Failure ")})     ,    remove:function (data) {This.ajax (" http://www.csdn.net/", data, function (Result) {    if (result.status) {alert ("Delete succeeded! ")} else {  alert (" Delete Failed ")}});  }} var singleton = null;  return {    getinstance:function () {      if (singleton = = null) {singleton = new Singletonclass ();      } else {return Singleton;}}}  ) ();


The Ajax method in Singleclass is also equivalent to a façade pattern (facade), which hides internal details and exposes an interface to the outside.















"JS design mode" uses a singleton mode (Singleton) to encapsulate the addition and deletion of data.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.