영어로 읽는 코딩

48_[자바] 다형성 (상속과 컴포지션을 이용)

Designing with inheritance

Once you learn about polymorphism, it can seem that everything ought to be inherited, because polymorphism is such a clever tool. This can burden your designs; in fact, if you choose inheritance first when you’re using an existing class to make a new class, things can become needlessly complicated.

A better approach is to choose composition first, especially when it’s not obvious which one you should use. Composition does not force a design into an inheritance hierarchy. But composition is also more flexible since it’s possible to dynamically choose a type (and thus behavior) when using composition, whereas inheritance requires an exact type to be known at compile time. The following example illustrates this:

 

//: polymorphism/Transmogrify.java
// Dynamically changing the behavior of an object
// via composition (the "State" design pattern).
import static net.mindview.util.Print.*;
class Actor {
    public void act() {}
}
class HappyActor extends Actor {
	public void act() { print("HappyActor"); }
}
class SadActor extends Actor {
	public void act() { print("SadActor"); }
}
class Stage {
	private Actor actor = new HappyActor();
	public void change() { actor = new SadActor(); }
	public void performPlay() { actor.act(); }
}
public class Transmogrify {
	public static void main(String[] args) {
		Stage stage = new Stage();
		stage.performPlay();
		stage.change();
		stage.performPlay();
}
} /* Output:
HappyActor
SadActor
*///:~

 

 

A Stage object contains a reference to an Actor, which is initialized to a HappyActor object. This means performPlay( ) produces a particular behavior. But since a reference can be rebound to a different object at run time, a reference for a SadActor object can be substituted in actor, and then the behavior produced by performPlay( ) changes. Thus you gain dynamic flexibility at run time. (This is also called the State Pattern. See Thinking in Patterns (with Java) at www.MindView.com.) In contrast, you can’t decide to inherit differently at run time; that must be completely determined at compile time.

A general guideline is “Use inheritance to express differences in behavior, and fields to express variations in state.” In the preceding example, both are used; two different classes are inherited to express the difference in the act( ) method, and Stage uses composition to allow its state to be changed. In this case, that change in state happens to produce a change in behavior.

 

 

[Thinking in Java, 212]

댓글

댓글 본문
작성자
비밀번호
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기