Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

装饰模式的疑问 #5

Copy link
Copy link
@robin-fei

Description

@robin-fei
Issue body actions

半透明装饰模式可以给系统带来更多的灵活性,设计相对简单,使用起来也非常方便;但是其最大的缺点在于不能实现对同一个对象的多次装饰,而且客户端需要有区别地对待装饰之前的对象和装饰之后的对象。在实现半透明的装饰模式时,我们只需在具体装饰类中增加一个独立的addedBehavior()方法来封装相应的业务处理,由于客户端使用具体装饰类型来定义装饰后的对象,因此可以单独调用addedBehavior()方法来扩展系统功能。
为什么半透明装饰模式不能实现对同一个对象的多次装饰????
对上面这句话问句不是很理解!!!
我的测试代码如下:

//Encryption.java
public abstract class Encryption {
    abstract String enc(String str);
}
//NormalEncrypt.java
public class NormalEncrypt extends Encryption {

    @Override
    String enc(String str) {
        System.out.println("move bit algorithm encryption");
        return str;
    }
}
//EncryptionDecorate.java
public class EncryptionDecorate extends Encryption {

    private Encryption encryption;

    public EncryptionDecorate(Encryption e) {
        this.encryption = e;
    }

    @Override
    String enc(String str) {
        encryption.enc(str);
        return str;
    }
}
//TwoEncryption.java
public class TwoEncryption extends EncryptionDecorate {

    public TwoEncryption(Encryption e) {
        super(e);
    }

    @Override
    String enc(String str) {
//        String s = super.enc(str);
//        return twoEnc(s);
        return super.enc(str);
    }

    private String twoEnc(String str) {
        System.out.println("twice encrypt");
        return str;
    }

    public void display(){
        System.out.println("show TwoEncryption");
    }
}
//ThreeEncryption.java
public class ThreeEncryption extends EncryptionDecorate {

    public ThreeEncryption(Encryption e) {
        super(e);
    }

    @Override
    String enc(String str) {
        String s = super.enc(str);
        return threeEnc(s);
    }

    private String threeEnc(String str) {
        System.out.println("third encrypt");
        return str;
    }
}

//App.java
public class App {

    public static void main(String[] args) {
        Encryption ne = new NormalEncrypt();
        TwoEncryption ed = new TwoEncryption(ne);
        //ed.enc("123");
        ed.display();
        Encryption et = new ThreeEncryption(ed);
        et.enc("123");
    }
}

以上代码打印的运行结果是 :
show TwoEncryption
move bit algorithm encryption
third encrypt

et对象还是依旧对ne原始对象进行装饰了的,请麻烦解惑下“半透明装饰模式不能实现对同一个对象的多次装饰”这句话,不胜感激!!!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.