Nice programing

실용적인 자바 스크립트 객체 지향 디자인 패턴의 예

nicepro 2020. 10. 5. 20:55
반응형

실용적인 자바 스크립트 객체 지향 디자인 패턴의 예


애플리케이션의 자바 스크립트에서 어떤 객체 지향 디자인 패턴을 사용하며 그 이유는 무엇입니까?

공식적인 디자인 패턴이 첨부되어 있지 않더라도 코드를 게시 할 수 있습니다.

나는 많은 자바 스크립트를 작성했지만 내가하는 일에 많은 객체 지향 패턴을 적용하지 않았으며 많은 것을 놓치고 있다고 확신합니다.


다음은 세 가지 인기있는 JavaScript 패턴입니다. 이는 클로저로 인해 쉽게 구현할 수 있습니다 .

다음 사항도 확인해보십시오.

다음은 Diaz가 발표 한 2008 년 Google I / O 강연으로 그의 책에서 몇 가지 주제에 대해 논의합니다.


계승

저는 ExtJS 3 기반의 상속에 대한 표기법을 사용하는데 , Java에서 고전적인 상속을 에뮬레이트하는 것과 매우 유사합니다. 기본적으로 다음과 같이 실행됩니다.

// Create an 'Animal' class by extending
// the 'Object' class with our magic method
var Animal = Object.extend(Object, {
    move : function() {alert('moving...');}
});

// Create a 'Dog' class that extends 'Animal'
var Dog = Object.extend(Animal, {
    bark : function() {alert('woof');}
});

// Instantiate Lassie
var lassie = new Dog();

// She can move and bark!
lassie.move();
lassie.bark();

네임 스페이스

또한 Eric Miraglia가 네임 스페이스를 고수하는 데 동의하므로 위의 코드는 창 개체 외부의 자체 컨텍스트 내에서 실행되어야합니다. 이는 코드가 브라우저 창에서 실행되는 여러 동시 프레임 워크 / 라이브러리 중 하나로 실행되도록하려는 경우 중요합니다.

즉, 창 개체에 대한 유일한 방법은 고유 한 네임 스페이스 / 모듈 개체를 사용하는 것입니다.

// Create a namespace / module for your project
window.MyModule = {};

// Commence scope to prevent littering 
// the window object with unwanted variables
(function() {

    var Animal = window.MyModule.Animal = Object.extend(Object, {
         move: function() {alert('moving...');}
    });

    // .. more code

})();

인터페이스

또한 인터페이스와 같은 고급 OOP 구조를 사용하여 애플리케이션 디자인을 향상시킬 수도 있습니다. 이것에 대한 나의 접근 방식Function.prototype다음 줄을 따라 표기법을 얻기 위해를 향상시키는 것 입니다.

var Dog = Object.extend(Animal, {
     bark: function() {
         alert('woof');
     }
     // more methods ..
}).implement(Mammal, Carnivore);

OO 패턴

Java 의미의 '패턴'에 관해서 는 사용자가 버튼을 클릭 할 때 일부 작업을 할당하는 것과 같은 이벤트 기반 기능 에 대해 Singleton 패턴 (캐싱에 적합)과 Observer 패턴 만 사용 했습니다.

관찰자 패턴 활용의 예는 다음과 같습니다.

// Instantiate object
var lassie = new Animal('Lassie');

// Register listener
lassie.on('eat', function(food) {
   this.food += food;
});

// Feed lassie by triggering listener
$('#feeding-button').click(function() {
    var food = prompt('How many food units should we give lassie?');
    lassie.trigger('eat', [food]);
    alert('Lassie has already eaten ' + lassie.food + ' units');
});

그리고 그것은 내 OO JS 가방에있는 몇 가지 트릭 일뿐입니다. 유용하기를 바랍니다.

I recommend if you intend to go down this road that you read Douglas Crockfords Javascript: the Good Parts. Its a brilliant book for this stuff.


I am a fan of the Module Pattern. It's a way of implementing extensible, non-dependent (most of the time) frameworks.

Example:

The framework, Q, is defined like this:

var Q = {};

To add a function:

Q.test = function(){};

These two lines of code are used together to form modules. The idea behind modules is that they all extend some base framework, in this case Q, but are not reliant on each other (if designed correctly) and can be included in any order.

In a module, you first create the framework object if it does not exist (which is an example of the Singleton pattern):

if (!Q)
    var Q = {};

Q.myFunction = function(){};

That way, you can have multiple modules (like the one above) in separate files, and include them in any order. Any one of them will create the framework object, and then extend it. No manual need to check if the framework exists. Then, to check if a module/function exists in custom code:

if (Q.myFunction)
    Q.myFunction();
else
    // Use a different approach/method

The singleton pattern is often very helpful for 'encapsulation' and organization stuff. You can even change accesibility.

var myInstance = {
  method1: function () {
    // ...
  },
  method2: function () {
    // ...
  }
};

cleanest way to implement a singleton in javascript


I really like jquery's method chaining pattern, allowing you to call several methods on one object. It makes it really easy to perform several operations in a single line of code.

Example:

$('#nav').click(function() {
   $(this).css('color','#f00').fadeOut();
});

I really like the Decorator pattern with jQuery plugins. Rather than modifying plugins to meet your needs, write a custom plugin that just forwards requests and adds additional parameters and functionality.

For example, if you need to pass a set of default arguments around all the time, and you need slightly-different behavior that ties into business logic, write a plugin that does whatever pre and post work is necessary to suit your needs and passes your default arguments if those particular arguments aren't specified.

The main benefit of this is that you can update your libraries and not worry about porting library changes. Your code might break, but there's at least the chance that it won't.


One of useful patterns in javascript world is chaining pattern which is made popular by LINQ at first place, and also is used in jQuery.

this pattern enables us to call different methods of a class in chaining manner.

the main structure of this pattern would be as

var Calaculator = function (init) {
    var result = 0;
    this.add = function (x) { result += (init + x); return this; };
    this.sub = function (x) { result += (init - x); return this; };
    this.mul = function (x) { result += (init * x); return this; };
    this.div = function (x) { result += (init / x); return this; };

    this.equals = function (callback) {
        callback(result);
    }

    return this;
};


new Calaculator(0)
    .add(10)
    .mul(2)
    .sub(5)
    .div(3)
    .equals(function (result) {
        console.log(result);
    });

the key idea of this pattern is this key word, which makes possible accessing to other public member of Calculator fucntion.

참고URL : https://stackoverflow.com/questions/3722820/examples-of-practical-javascript-object-oriented-design-patterns

반응형