1, Singleton pattern.
- Singleton pattern là mẫu thiết kế rất phổ biến nằm trong nhóm Creational pattern.
Mẫu thiết kế này được tạo ra để đảm bảo rằng:
- Một class chỉ có thể là một đối tượng.
- Một class chỉ được instance một đối tượng.
- Thể hiện truy cập của một đối tượng dễ dàng.
- Kiểm soát được khởi tạo của chúng nó.
2, Triển khai singleton pattern trên javascript.
javascript old style
var mySingleton = (function () { var instance; function init() { function privateMethod() { return 'private method'; } var privateVariable = "private property"; return { publicMethod: function () { return 'public method'; }, publicProperty: "public property", getPrivateMethod: function () { return privateMethod(); } }; }; return { getInstance: function () { if (!instance) { instance = init(); } return instance; } }; })(); //use var myInstance = mySingleton.getInstance(); console.log(myInstance.publicMethod()); console.log(myInstance.publicProperty); console.log(myInstance.getPrivateMethod()); ECMA2015 style (ES6)
class Singleton { constructor() { if (!this.instance) { this.instance = this; } return this.instance; } getName() { return 'Name'; } } //use var mySing = new Singleton(); console.log(mySing.getName());
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!



0 Comments