美文网首页
设计模式-?组合模式

设计模式-?组合模式

作者: IAmWhoAmI | 来源:发表于2016-07-28 09:46 被阅读2次

    自己管理自己

    
    abstract class Employer{
        private String name;
        public void setName(String name){
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
        public abstract void add(Employer employer);
        public abstract void delete(Employer employer);
    
        public List employers;
    
        public void printInfo(){
            System.out.println(name);
        }
        public List getEmployers(){
            return this.employers;
        }
    }
    
    class Programmer extends Employer{
       public Programmer(String name){
           setName(name);
           employers = null;
       }
        public void add(Employer employer){}
        public void delete(Employer employer){}
    
    }
    
    class ProjectAssistant extends Employer{
        public ProjectAssistant(String name){
            setName(name);
            employers =null;
        }
        public void add(Employer employer){}
        public void delete(Employer employer){}
    }
    
    class ProjectManager extends Employer{
        public ProjectManager(String name){
            setName(name);
            employers = new ArrayList();
        }
        public void add(Employer employer){
            employers.add(employer);
        }
        public void delete(Employer employer){
            employers.remove(employer);
        }
    }
    
    public class ComponentTest {
        public static void main(String[] args){
            Employer pm =new ProjectManager("pm");
            Employer pa = new ProjectAssistant("pa");
            Employer p1 = new Programmer("p1");
            Employer p2 = new Programmer("p2");
    
            pm.add(pa);
            pm.add(p2);
    
            List ems = pm.getEmployers();
            for(Object em:ems){
                System.out.println(((Employer)em).getName());
            }
    
        }
    }
    

    相关文章

      网友评论

          本文标题:设计模式-?组合模式

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