装饰模式

作者: Airycode | 来源:发表于2018-05-07 14:52 被阅读7次

先不谈设计模式,需求是写一个可以给人搭配不同的服饰的系统,比如类似QQ,网络游戏或者论坛都有的Avatar系统。怎么开发?
第一版代码:

package 装饰模式;

public class Person1 {

    private String name;
    
    public Person1(String name){
        this.name = name;
    }
    
    public void WearTShirts(){
        System.out.println("大T");
    }
    
    public void WearBigTrouser(){
        System.out.println("垮裤");
    }
    
    public void WearSneakers(){
        System.out.println("破球鞋");
    }
    
    public void WearSuit(){
        System.out.println("西装");
    }
    
    public void WearTie(){
        System.out.println("领带");
    }
    
    public void WearLeatherShoes(){
        System.out.println("皮鞋");
    }
    
    public void Show(){
        System.out.println(name);
    }
}

package 装饰模式;

public class Person1App {

    public static void main(String[] args) {
        Person1 person1 = new Person1("小菜");
        person1.WearTShirts();
        person1.WearBigTrouser();
        person1.WearSneakers();
        person1.Show();
        
        System.out.println("-----------------------");
        person1.WearSuit();
        person1.WearTie();
        person1.WearLeatherShoes();
        person1.Show();
    }
    
}


哈哈不错功能是实现了,现在的问题就是如果我需要增加‘超人’的装扮,你得如何做?
那就修改Person1类,这样就违背了开放-封闭原则。应该如何做,把这些服饰写成一个子类

相关文章

网友评论

    本文标题:装饰模式

    本文链接:https://www.haomeiwen.com/subject/xinmrftx.html