我对decorate模式的理解:
1-首先要有一个Interface,提供一个通用的方法;
2-其次有n多个class来实现这个接口中的方法,这些实现方法在功能上应该是并列的,但不是必须的,从而可以根据需要decorate那个需要被修饰的初始对象。
3-最后这些class都有一个带有Interface作为参数的构造方法和一个Interface的属性,这样在构造的时候就可以取得那个需要修饰的对象的实例,然后在实现Interface的方法里面,首先实现修饰对象实例的修饰方法,然后再进行自己的decorate方法。
根据这个想法来画一张画:
package test;
public interface Painting {
public void paint();
}
class SunPainting implements Painting {
Painting painting = null ;
public SunPainting() {
}
public SunPainting(Painting painting) {
this .painting = painting;
}
public void paint() {
if (painting != null ) {
painting.paint();
}
System.out.println( " 画了一个太阳 " );
}
}
class CloudPainting implements Painting {
Painting painting = null ;
public CloudPainting() {
}
public CloudPainting(Painting painting) {
this .painting = painting;
}
public void paint() {
if (painting != null ) {
painting.paint();
}
System.out.println( " 画了一朵白云 " );
}
}
class LawnPainting implements Painting {
Painting painting = null ;
public LawnPainting() {
}
public LawnPainting(Painting painting) {
this .painting = painting;
}
public void paint() {
if (painting != null ) {
painting.paint();
}
System.out.println( " 画了一片草地 " );
}
}
public interface Painting {
public void paint();
}
class SunPainting implements Painting {
Painting painting = null ;
public SunPainting() {
}
public SunPainting(Painting painting) {
this .painting = painting;
}
public void paint() {
if (painting != null ) {
painting.paint();
}
System.out.println( " 画了一个太阳 " );
}
}
class CloudPainting implements Painting {
Painting painting = null ;
public CloudPainting() {
}
public CloudPainting(Painting painting) {
this .painting = painting;
}
public void paint() {
if (painting != null ) {
painting.paint();
}
System.out.println( " 画了一朵白云 " );
}
}
class LawnPainting implements Painting {
Painting painting = null ;
public LawnPainting() {
}
public LawnPainting(Painting painting) {
this .painting = painting;
}
public void paint() {
if (painting != null ) {
painting.paint();
}
System.out.println( " 画了一片草地 " );
}
}
再写段测试画画的代码:
package test;
public class TestPainting {
public static void main(String[] args) {
new SunPainting( new CloudPainting( new LawnPainting())).paint();
}
}
public class TestPainting {
public static void main(String[] args) {
new SunPainting( new CloudPainting( new LawnPainting())).paint();
}
}
测试结果:
画了一片草地
画了一朵白云
画了一个太阳
画了一朵白云
画了一个太阳
最后有个问题:为什么不直接定义一个画画的类,然后把这些该怎么画的事情分别通过方法来实现呢? 那么什么情况下使用decorate模式更为合适呢?