[위키] 데코레이터 패턴

javascript 2012. 12. 27. 13:21 Posted by jiddong

데코레이터 패턴

위키백과, 우리 모두의 백과사전.

데코레이터 패턴(Decorator pattern)이란 주어진 상황 및 용도에 따라 어떤 객체에 책임을 덧붙이는 패턴으로, 기능 확장이 필요할 때 서브클래싱 대신 쓸 수 있는 유연한 대안이 될 수 있다.

목차

  [숨기기

[편집]

[편집]자바

// the Window interface
interface Window {
    public void draw(); // draws the Window
    public String getDescription(); // returns a description of the Window
}
 
 
// implementation of a simple Window without any scrollbars
class SimpleWindow implements Window {
    public void draw() {
        // draw window
    }
 
    public String getDescription() {
        return "simple window";
    }
}

아래의 클래스들은 모든 Window 클래스들의 데코레이터를 포함하고 있다.

// abstract decorator class - note that it implements Window
abstract class WindowDecorator implements Window {
    protected Window decoratedWindow; // the Window being decorated
 
    public WindowDecorator (Window decoratedWindow) {
        this.decoratedWindow = decoratedWindow;
    }
}
 
 
// the first concrete decorator which adds vertical scrollbar functionality
class VerticalScrollBarDecorator extends WindowDecorator {
    public VerticalScrollBarDecorator (Window decoratedWindow) {
        super(decoratedWindow);
    }
 
    public void draw() {
        drawVerticalScrollBar();
        decoratedWindow.draw();
    }
 
    private void drawVerticalScrollBar() {
        // draw the vertical scrollbar
    }
 
    public String getDescription() {
        return decoratedWindow.getDescription() + ", including vertical scrollbars";
    }
}
 
 
// the second concrete decorator which adds horizontal scrollbar functionality
class HorizontalScrollBarDecorator extends WindowDecorator {
    public HorizontalScrollBarDecorator (Window decoratedWindow) {
        super(decoratedWindow);
    }
 
    public void draw() {
        drawHorizontalScrollBar();
        decoratedWindow.draw();
    }
 
    private void drawHorizontalScrollBar() {
        // draw the horizontal scrollbar
    }
 
    public String getDescription() {
        return decoratedWindow.getDescription() + ", including horizontal scrollbars";
    }
}

Window 인스터스를 만드는 테스트 프로그램은 아래와 같다.

public class DecoratedWindowTest {
    public static void main(String[] args) {
        // create a decorated Window with horizontal and vertical scrollbars
        Window decoratedWindow = new HorizontalScrollBarDecorator (
                new VerticalScrollBarDecorator(new SimpleWindow()));
 
        // print the Window's description
        System.out.println(decoratedWindow.getDescription());
    }
}

[편집]C++

#include <iostream>
 
using namespace std;
 
/* Component (interface) */
class Widget {
 
public: 
  virtual void draw() = 0; 
  virtual ~Widget() {}
};  
 
/* ConcreteComponent */
class TextField : public Widget {
 
private:                  
   int width, height;
 
public:
   TextField( int w, int h ){ 
      width  = w;
      height = h; 
   }
 
   void draw() { 
      cout << "TextField: " << width << ", " << height << '\n'; 
   }
};
 
/* Decorator (interface) */                                           
class Decorator : public Widget {
 
private:
   Widget* wid;       // reference to Widget
 
public:
   Decorator( Widget* w )  { 
     wid = w; 
   }
 
   void draw() { 
     wid->draw(); 
   }
 
   ~Decorator() {
     delete wid;
   }
};
 
/* ConcreteDecoratorA */
class BorderDecorator : public Decorator { 
 
public:
   BorderDecorator( Widget* w ) : Decorator( w ) { }
   void draw() {
      Decorator::draw();    
      cout << "   BorderDecorator" << '\n'; 
   }  
};
 
/* ConcreteDecoratorB */
class ScrollDecorator : public Decorator { 
public:
   ScrollDecorator( Widget* w ) : Decorator( w ) { }
   void draw() {
      Decorator::draw(); 
      cout << "   ScrollDecorator" << '\n';
   }  
};
 
int main( void ) {
 
   Widget* aWidget = new BorderDecorator(
                     new ScrollDecorator(
                     new TextField( 80, 24 )));
   aWidget->draw();
   delete aWidget;
}

[편집]C#

namespace GSL_Decorator_pattern
{
        interface IWindowObject
        {
                void draw(); // draws the object
                String getDescription(); // returns a description of the object
        }
 
 
        class ControlComponent : IWindowObject
        {
                public ControlComponent()
                {
                }
 
                public void draw() // draws the object
                {
                        Console.WriteLine( "ControlComponent::draw()" ); 
                }
 
                public String getDescription() // returns a description of the object
                {
                        return "ControlComponent::getDescription()";
                }
        }
 
        abstract class Decorator : IWindowObject
        {
                protected IWindowObject _decoratedWindow = null; // the object being decorated
 
                public Decorator( IWindowObject decoratedWindow )
                {
                        _decoratedWindow = decoratedWindow;
                }
 
                public virtual void draw()
                {
                        _decoratedWindow.draw();
                        Console.WriteLine("\tDecorator::draw() ");
                }
 
                public virtual String getDescription() // returns a description of the object
                {
                        return _decoratedWindow.getDescription() + "\n\t" + "Decorator::getDescription() ";
                }
        }
 
        // the first decorator 
        class DecorationA : Decorator
        {
                public DecorationA(IWindowObject decoratedWindow) : base(decoratedWindow)
                {
                }
 
                public override void draw()
                {
                        base.draw();
                        DecorationAStuff();
                }
 
                private void DecorationAStuff()
                {
                        Console.WriteLine("\t\tdoing DecorationA things");
                }
 
                public override String getDescription()
                {
                        return base.getDescription() + "\n\t\tincluding " + this.ToString();
                }
 
        }// end  class ConcreteDecoratorA : Decorator
 
        class DecorationB : Decorator
        {
                public DecorationB(IWindowObject decoratedWindow) : base(decoratedWindow)
                {
                }
 
                public override void draw()
                {
                        base.draw();
                        DecorationBStuff();
                }
 
                private void DecorationBStuff()
                {
                        Console.WriteLine("\t\tdoing DecorationB things");
                }
 
                public override String getDescription()
                {
                        return base.getDescription() + "\n\t\tincluding " + this.ToString();
                }
 
        }// end  class DecorationB : Decorator
 
        class DecorationC : Decorator
        {
                public DecorationC(IWindowObject decoratedWindow) : base(decoratedWindow)
                {
                }
 
                public override void draw()
                {
                        base.draw();
                        DecorationCStuff();
                }
 
                private void DecorationCStuff()
                {
                        Console.WriteLine("\t\tdoing DecorationC things");
                }
 
                public override String getDescription()
                {
                        return base.getDescription() + "\n\t\tincluding " + this.ToString();
                }
 
        }// end  class DecorationC : Decorator
 
}// end of namespace GSL_Decorator_pattern

[편집]파이썬

class Coffee:
    def cost(self):
        return 1
 
class Milk:
    def __init__(self, coffee):
        self.coffee = coffee
 
    def cost(self):
        return self.coffee.cost() + .5
 
class Whip:
    def __init__(self, coffee):
        self.coffee = coffee
 
    def cost(self):
        return self.coffee.cost() + .7
 
class Sprinkles:
    def __init__(self, coffee):
        self.coffee = coffee
 
    def cost(self):
        return self.coffee.cost() + .2
 
# Example 1
coffee = Milk(Coffee())
print "Coffee with milk : "+str(coffee.cost())
 
# Example 2
coffee = Whip(Milk(Sprinkles(Coffee())))
print "Coffee with milk, whip and sprinkles : "+str(coffee.cost())

[편집]자바스크립트

//Class to be decorated
function Coffee(){
    this.cost = function(){
        return 1;
    };
}
 
//Decorator A
function Milk(coffee){
    this.cost = function(){
        return coffee.cost() + 0.5;
    };  
}
 
//Decorator B
function Whip(coffee){
    this.cost = function(){
        return coffee.cost() + 0.7;
    };
}
 
//Decorator C
function Sprinkles(coffee){
    this.cost = function(){
        return coffee.cost() + 0.2;
    };
}
 
//Here's one way of using it
var coffee = new Milk(new Whip(new Sprinkles(new Coffee())));
alert( coffee.cost() );
 
//Here's another
var coffee = new Coffee();
coffee = new Sprinkles(coffee);
coffee = new Whip(coffee);
coffee = new Milk(coffee);
alert(coffee.cost());


출처 위키 피디아

http://ko.wikipedia.org/wiki/%EB%8D%B0%EC%BD%94%EB%A0%88%EC%9D%B4%ED%84%B0_%ED%8C%A8%ED%84%B4

[위키]팩토리 메서드 패턴

javascript 2012. 12. 27. 13:19 Posted by jiddong

팩토리 메서드 패턴

위키백과, 우리 모두의 백과사전.
UML로 표현된 팩토리 메서드
LePUS3로 표현된 펙토리 메서드

팩토리 메서드 패턴(Factory method pattern)은 객체지향 디자인 패턴이다. 다른 생성 패턴들처럼, 이 패턴도 생성하려는 객체의 클래스를 정확히 지정하지 않으면서 객체를 만드는 문제를 다룬다. 팩토리 메서드 패턴은 이 문제를 객체를 만드는 또 다른 메서드를 정의하여 처리한다. 일반적으로, 팩토리 메서드라는 용어는 객체를 만드는 것이 주 목적인 메서드를 지칭하는데 주로 사용한다.

목차

  [숨기기

[편집]

[편집]C#

Pizza example:

public abstract class Pizza
{
    public abstract decimal GetPrice();
 
    public enum PizzaType
    {
        HamMushroom, Deluxe, Seafood
    }
    public static Pizza PizzaFactory(PizzaType pizzaType)
    {
        switch (pizzaType)
        {
            case PizzaType.HamMushroom:
                return new HamAndMushroomPizza();
 
            case PizzaType.Deluxe:
                return new DeluxePizza();
 
            case PizzaType.Seafood:
                return new SeafoodPizza();
 
        }
 
        throw new System.NotSupportedException("The pizza type " + pizzaType.ToString() + " is not recognized.");
    }
}
public class HamAndMushroomPizza : Pizza
{
    private decimal price = 8.5M;
    public override decimal GetPrice() { return price; }
}
 
public class DeluxePizza : Pizza
{
    private decimal price = 10.5M;
    public override decimal GetPrice() { return price; }
}
 
public class SeafoodPizza : Pizza
{
    private decimal price = 11.5M;
    public override decimal GetPrice() { return price; }
}
 
// Somewhere in the code
...
  Console.WriteLine( Pizza.PizzaFactory(Pizza.PizzaType.Seafood).GetPrice().ToString("C2") ); // $11.50
...

[편집]자바스크립트

Pizza example:

//Our pizzas
function HamAndMushroomPizza(){
  var price = 8.50;
  this.getPrice = function(){
    return price;
  }
}
 
function DeluxePizza(){
  var price = 10.50;
  this.getPrice = function(){
    return price;
  }
}
 
function SeafoodPizza(){
  var price = 11.50;
  this.getPrice = function(){
    return price;
  }
}
 
//Pizza Factory
function PizzaFactory(){
  this.createPizza = function(type){
     switch(type){
      case "Ham and Mushroom":
        return new HamAndMushroomPizza();
      case "DeluxePizza":
        return new DeluxePizza();
      case "Seafood Pizza":
        return new SeafoodPizza();
      default:
          return new DeluxePizza();
     }     
  }
}
 
//Usage
var pizzaPrice = new PizzaFactory().createPizza("Ham and Mushroom").getPrice();
alert(pizzaPrice);

[편집]

출처 위키 피디아 

http://ko.wikipedia.org/wiki/%ED%8C%A9%ED%86%A0%EB%A6%AC_%EB%A9%94%EC%84%9C%EB%93%9C_%ED%8C%A8%ED%84%B4

'javascript' 카테고리의 다른 글

CSS 셀렉터  (0) 2015.03.02
[위키] 데코레이터 패턴  (0) 2012.12.27
[Javascript] IOS WebView Ajax return page call init funtion issue  (0) 2012.09.19
JavaScript-Garden 한글  (0) 2012.08.17
JSDT (Java script 코드 어시스트)  (0) 2012.08.17

Eclipse 자동 주석 설정

eclipse 2012. 12. 14. 11:11 Posted by jiddong

위치 

Window -> Preferences -> Java  -> Code Style -> Code Templates -> Comments 

Window -> Preferences -> JavaScript  -> Code Style -> Code Templates -> Comments 



Function or method  설정  예시


/**

 * @package : ${package_name}/${file_name}

 * @author : ${user}  

 * @date : ${date}

 * ${tags}

 * ${enclosing_type}

 */


메소드에서 주석 생성하면 이런 식으로 나옴


/**

 * 현재 패스가 폰인지 패드인지 확인 

 * @package : js/schedule/phone/scheduleList.java

 * @author : 이름

 * @date : 2012. 12. 13.

 * @returns {Boolean}

 *

 */


${}  상세 내용설명

data : Current date (현재 날짜)

dollar : The dollar symbol (달러문양)

enclosing_type :The type enclosing the method (선택된 메소드의 타입)

file_name : Name of the enclosing compilation (선택된 편집파일 이름)

package_name : Name of the enclosing package (선택된 패키지 이름)

project_name : Name of the enclosing project (선택된 프로젝트 이름)

tags : Generated Javadoc tags (@param, @return...) (Javedoc 태그 생성)

time : Current time (현재 시간)

todo : Todo task tag ('해야할일'태그 생성)

type_name : Name of the current type (현재 타입의 이름)

user : User name (사용자 이름)

year : Current year (현재 연도)



참조 블로그