Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

装饰模式的疑问 #5

Open
robin-fei opened this issue May 6, 2018 · 0 comments
Open

装饰模式的疑问 #5

robin-fei opened this issue May 6, 2018 · 0 comments

Comments

@robin-fei
Copy link

半透明装饰模式可以给系统带来更多的灵活性,设计相对简单,使用起来也非常方便;但是其最大的缺点在于不能实现对同一个对象的多次装饰,而且客户端需要有区别地对待装饰之前的对象和装饰之后的对象。在实现半透明的装饰模式时,我们只需在具体装饰类中增加一个独立的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原始对象进行装饰了的,请麻烦解惑下“半透明装饰模式不能实现对同一个对象的多次装饰”这句话,不胜感激!!!

gitbook-com bot pushed a commit to 1119264845/design-pattern-java that referenced this issue Aug 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant