티스토리 툴바


블로그 이미지
카라크라스

Leon.Kim의 공부하는 블로그입니다. mail - kalaklas@gmail.com twitter - @kalaklas

Rss feed Tistory
Java/DesignPattern 2009/08/19 00:05

Fundamental Design Patterns

Fundamental Design Patterns

-Delegation Pattern
 Delegation이라는 영어 단어 자체의 뜻이 "위임" 이라는 것을 고려해보면 Delegation은 어떤 동작을 자신이 직접 수행하지 않고 다른 것 (method, object, etc)에게 위임한다는 것이다.
객체가 할 행동을 객체 자신을 수정하지 않고 Delegation을 수정 (또는 재 정의) 함으로써 가능하다 (확장성).
  • 이 것은 프로그램이 거대해지고 복잡해질 수록 효과를 발휘할 것이다.
  • 또한 동적으로 객체의 행위를 변경하기 용이할 것이다.
  • 또한 프로그램이 fron-end가 아닌 framework이고 API interface를 제공하는 입장이라면 Delegation은 단순히 효과 적인 기법이 아닌 확장 (테스팅 포함)을 위한 필수 조건일 수도 있다. 
 

interface I {
void f();
void g();
}

class A implements I {
public void f() { System.out.println("A: doing f()"); }
public void g() { System.out.println("A: doing g()"); }
}

class B implements I {
public void f() { System.out.println("B: doing f()"); }
public void g() { System.out.println("B: doing g()"); }
}

class C implements I {
// delegation
I i = new A();

public void f() { i.f(); }
public void g() { i.g(); }

// normal attributes
void toA() { i = new A(); }
void toB() { i = new B(); }
}


public class Main {
public static void main(String[] args) {
C c = new C();
c.f(); // output: A: doing f()
c.g(); // output: A: doing g()
c.toB();
c.f(); // output: B: doing f()
c.g(); // output: B: doing g()
}
}
출처 :> http://en.wikipedia.org/wiki/Delegation_pattern 위키피디아



-Immutable Pattern
이뮤터블 패턴의 개념은 한마디로 표현할 수 있다. 한번 만든 객체는 변형하지 않으며, 변형이 발생할 때는 새로운 객체를 만든다는 것. 
Java의 String객체는 String이 변형될때 새로인 객체가 만들어진다.

Example>
String a = "a";
String b = "b";

String ab = a+b;

위의 경우 ab객체는 a와 b 객체가 합쳐진 객체가 아니라, 새로 생성된 객체이다.

String은 Java에서의 대표적인 Immutable Object이다. 
한번 인스턴싱된 객체는 변형되지 않으며, 변형이 발생할 때는 새로운 객체가 인스턴싱된다.

class Cart {
private final List items;

public Cart(List items) { this.items = items; }

public List getItems() { return items; }
public int total() { /* return sum of the prices */ }
}


class ImmutableCart {
private final List items;

public ImmutableCart(List items) {
this.items = Collections.unmodifiableList(new ArrayList(items));
}

public List getItems() {
return items;
}
public int total() { /* return sum of the prices */ }
}

출처 : http://en.wikipedia.org/wiki/Immutable_pattern 위키피디아


- Marker Interface
*What is Maker Interface?
Serializable 인터페이스 같이 구현이 필요없는(아무것도 구현하지 않을 인터페이스) 인터페이스를 Maker Interface라고 한다.
(Serializable interface? >> )

말그대로 표시해주는 역할을 하는 interface를 implements한다.
내가 정한 표시로 내가 원하는 클래스를 구별할수 있다.


*Why Use Maker Interface?
적절한 예시가 될런지 모르겠지만;;;;

public interface Korea{}
public interface Japan{}
public interface China{}

 이렇게 세 종류의 구현이 필요없는 인터페이스가 세개 있다고 했을 때,

여러종류의 Product Object들이 있을때 (자동차, 자전거, 세탁기등등등 )
각각의 생산 국가를 마킹하기 위해 

public Vehicle implements Korea{.........}
pubic Bycycle implements China{.........}
요런식으로 . . . 마킹을 한다.

요걸 Maker Interface Pattern이라 한다

In java language programming, interfaces with no methods are known as marker interfaces. Marker interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality.

e.g.  Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.  

Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super class, then a call to the method clone() on Myclass's object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.




- Proxy Pattern
Proxy의 사전적 의미는 대리, 위임이다.


import java.util.*;

interface Image {
public void displayImage();
}

//on System A
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadImageFromDisk();
}

private void loadImageFromDisk() {
System.out.println("Loading " + filename);
}

public void displayImage() {
System.out.println("Displaying " + filename);
}
}

//on System B
class ProxyImage implements Image {
private String filename;
private Image image;

public ProxyImage(String filename) {
this.filename = filename;
}
public void displayImage() {
image = new RealImage(filename);
image.displayImage();
}
}

class ProxyExample {
public static void main(String[] args) {
Image image1 = new ProxyImage("HiRes_10MB_Photo1");
Image image2 = new ProxyImage("HiRes_10MB_Photo2");

image1.
displayImage(); // loading necessary
image2.displayImage(); // loading necessary
}
}

출처 : http://en.wikipedia.org/wiki/Proxy_pattern 위키피디아 

>>Proxy패턴은 Decorator패턴과 유사하여 혼동되기도 합니다.
하지만 두가지 패턴은 서로 다른 목적을 가진 패턴들입니다.

*Proxy패턴은 기존에 구현되어있는 기능(객체)에 보다 효율적으로 접근, 원격 제어, 접근 권한 제어하는것 등이 목적입니다.
*Decorator패턴은 구현되어 있는 기능에 새로운 기능의 추가를 쉽게하는 것이 주요 목적입니다.


'Java > DesignPattern' 카테고리의 다른 글

inheritance and composition on Java  (0) 2011/02/08
행동패턴 - 책임 연쇄 (chain of responsibility)  (0) 2010/11/25
Creational Pattern  (0) 2009/10/15
Fundamental Design Patterns  (0) 2009/08/19
TOTAL 19,751 TODAY 3