复合模式2 : 复合模式 « 设计模式 « Java

En
Java
1. 图形用户界面
2. 三维图形动画
3. 高级图形
4. 蚂蚁编译
5. Apache类库
6. 统计图
7. 
8. 集合数据结构
9. 数据类型
10. 数据库JDBC
11. 设计模式
12. 开发相关类
13. EJB3
14. 电子邮件
15. 事件
16. 文件输入输出
17. 游戏
18. 泛型
19. GWT
20. Hibernate
21. 本地化
22. J2EE平台
23. 基于J2ME
24. JDK-6
25. JNDI的LDAP
26. JPA
27. JSP技术
28. JSTL
29. 语言基础知识
30. 网络协议
31. PDF格式RTF格式
32. 映射
33. 常规表达式
34. 脚本
35. 安全
36. Servlets
37. Spring
38. Swing组件
39. 图形用户界面
40. SWT-JFace-Eclipse
41. 线程
42. 应用程序
43. Velocity
44. Web服务SOA
45. 可扩展标记语言
Java 教程
Java » 设计模式 » 复合模式屏幕截图 
复合模式2

//[C] 2002 Sun Microsystems, Inc.---
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

public class RunCompositePattern {
    public static void main(String [] arguments){
        System.out.println("Example for the Composite pattern");
        System.out.println();
        System.out.println("This code sample will propagate a method call throughout");
        System.out.println(" a tree structure. The tree represents a project, and is");
        System.out.println(" composed of three kinds of ProjectItems - Project, Task,");
        System.out.println(" and Deliverable. Of these three classes, Project and Task");
        System.out.println(" can store an ArrayList of ProjectItems. This means that");
        System.out.println(" they can act as branch nodes for our tree. The Deliverable");
        System.out.println(" is a terminal node, since it cannot hold any ProjectItems.");
        System.out.println();
        System.out.println("In this example, the method defined by ProjectItem,");
        System.out.println(" getTimeRequired, provides the method to demonstrate the");
        System.out.println(" pattern. For branch nodes, the method will be passed on");
        System.out.println(" to the children. For terminal nodes (Deliverables), a");
        System.out.println(" single value will be returned.");
        System.out.println();
        System.out.println("Note that it is possible to make this method call ANYWHERE");
        System.out.println(" in the tree, since all classes implement the getTimeRequired");
        System.out.println(" method. This means that you are able to calculate the time");
        System.out.println(" required to complete the whole project OR any part of it.");
        System.out.println();
        
        System.out.println("Deserializing a test Project for the Composite pattern");
        System.out.println();
        if (!(new File("data.ser").exists())){
            DataCreator.serialize("data.ser");
        }
        Project project = (Project)(DataRetriever.deserializeData("data.ser"));
        
        System.out.println("Calculating total time estimate for the project");
        System.out.println("\t" + project.getDescription());
        System.out.println("Time Required: " + project.getTimeRequired());
        
    }
}
interface Contact extends Serializable{
    public static final String SPACE = " ";
    public String getFirstName();
    public String getLastName();
    public String getTitle();
    public String getOrganization();
    
    public void setFirstName(String newFirstName);
    public void setLastName(String newLastName);
    public void setTitle(String newTitle);
    public void setOrganization(String newOrganization);
}

class ContactImpl implements Contact{
    private String firstName;
    private String lastName;
    private String title;
    private String organization;
    
    public ContactImpl(){}
    public ContactImpl(String newFirstName, String newLastName,
        String newTitle, String newOrganization){
            firstName = newFirstName;
            lastName = newLastName;
            title = newTitle;
            organization = newOrganization;
    }
    
    public String getFirstName(){ return firstName; }
    public String getLastName(){ return lastName; }
    public String getTitle(){ return title; }
    public String getOrganization(){ return organization; }
    
    public void setFirstName(String newFirstName){ firstName = newFirstName; }
    public void setLastName(String newLastName){ lastName = newLastName; }
    public void setTitle(String newTitle){ title = newTitle; }
    public void setOrganization(String newOrganization){ organization = newOrganization; }
    
    public String toString(){
        return firstName + SPACE + lastName;
    }
}

class DataCreator{
    private static final String DEFAULT_FILE = "data.ser";
    
    public static void main(String [] args){
        String fileName;
        if (args.length == 1){
            fileName = args[0];
        }
        else{
            fileName = DEFAULT_FILE;
        }
        serialize(fileName);
    }
    
    public static void serialize(String fileName){
        try{
            serializeToFile(createData(), fileName);
        }
        catch (IOException exc){
            exc.printStackTrace();
        }
    }
    
    private static Serializable createData(){
        Contact contact1 = new ContactImpl("Dennis""Moore""Managing Director""Highway Man, LTD");
        Contact contact2 = new ContactImpl("Joseph""Mongolfier""High Flyer""Lighter than Air Productions");
        Contact contact3 = new ContactImpl("Erik""Njoll""Nomad without Portfolio""Nordic Trek, Inc.");
        Contact contact4 = new ContactImpl("Lemming""""Principal Investigator""BDA");
        
        Project project = new Project("IslandParadise""Acquire a personal island paradise");
        Deliverable deliverable1 = new Deliverable("Island Paradise""", contact1);
        Task task1 = new Task("Fortune""Acquire a small fortune", contact4, 11.0);
        Task task2 = new Task("Isle""Locate an island for sale", contact2, 7.5);
        Task task3 = new Task("Name""Decide on a name for the island", contact3, 3.2);
        project.addProjectItem(deliverable1);
        project.addProjectItem(task1);
        project.addProjectItem(task2);
        project.addProjectItem(task3);
        
        Deliverable deliverable11 = new Deliverable("$1,000,000""(total net worth after taxes)", contact1);
        Task task11 = new Task("Fortune1""Use psychic hotline to predict winning lottery numbers", contact4, 2.5);
        Task task12 = new Task("Fortune2""Invest winnings to ensure 50% annual interest", contact1, 14.0);
        task1.addProjectItem(task11);
        task1.addProjectItem(task12);
        task1.addProjectItem(deliverable11);
        
        Task task21 = new Task("Isle1""Research whether climate is better in the Atlantic or Pacific", contact1, 1.8);
        Task task22 = new Task("Isle2""Locate an island for auction on EBay", contact4, 5.0);
        Task task23 = new Task("Isle2a""Negotiate for sale of the island", contact3, 17.5);
        task2.addProjectItem(task21);
        task2.addProjectItem(task22);
        task2.addProjectItem(task23);
        
        Deliverable deliverable31 = new Deliverable("Island Name""", contact1);
        task3.addProjectItem(deliverable31);
        return project;
    }
    
    private static void serializeToFile(Serializable content, String fileNamethrows IOException{
        ObjectOutputStream serOut = new ObjectOutputStream(new FileOutputStream(fileName));
        serOut.writeObject(content);
        serOut.close();
    }
}

class DataRetriever{
    public static Object deserializeData(String fileName){
        Object returnValue = null;
        try{
            File inputFile = new File(fileName);
            if (inputFile.exists() && inputFile.isFile()){
                ObjectInputStream readIn = new ObjectInputStream(new FileInputStream(fileName));
                returnValue = readIn.readObject();
                readIn.close();
            }else{
                System.err.println("Unable to locate the file " + fileName);
            }
        }catch (ClassNotFoundException exc){
            exc.printStackTrace();
            
        }catch (IOException exc){
            exc.printStackTrace();
        }
        return returnValue;
    }
}

class Deliverable implements ProjectItem{
    private String name;
    private String description;
    private Contact owner;
    
    public Deliverable(){ }
    public Deliverable(String newName, String newDescription,
        Contact newOwner){
        name = newName;
        description = newDescription;
        owner = newOwner;
    }
    
    public String getName(){ return name; }
    public String getDescription(){ return description; }
    public Contact getOwner(){ return owner; }
    public double getTimeRequired(){ return 0}
    
    public void setName(String newName){ name = newName; }
    public void setDescription(String newDescription){ description = newDescription; }
    public void setOwner(Contact newOwner){ owner = newOwner; }
}

class Project implements ProjectItem{
    private String name;
    private String description;
    private ArrayList projectItems = new ArrayList();
    
    public Project(){ }
    public Project(String newName, String newDescription){
        name = newName;
        description = newDescription;
    }    
    
    public String getName(){ return name; }
    public String getDescription(){ return description; }
    public ArrayList getProjectItems(){ return projectItems; }
    public double getTimeRequired(){
        double totalTime = 0;
        Iterator items = projectItems.iterator();
        while(items.hasNext()){
            ProjectItem item = (ProjectItem)items.next();
            totalTime += item.getTimeRequired();
        }
        return totalTime;
    }
    
    public void setName(String newName){ name = newName; }
    public void setDescription(String newDescription){ description = newDescription; }
    
    public void addProjectItem(ProjectItem element){
        if (!projectItems.contains(element)){
            projectItems.add(element);
        }
    }
    public void removeProjectItem(ProjectItem element){
        projectItems.remove(element);
    }
}

interface ProjectItem extends Serializable{
    public double getTimeRequired();
}

class Task implements ProjectItem{
    private String name;
    private String details;
    private ArrayList projectItems = new ArrayList();
    private Contact owner;
    private double timeRequired;
    
    public Task(){ }
    public Task(String newName, String newDetails,
        Contact newOwner, double newTimeRequired){
        name = newName;
        details = newDetails;
        owner = newOwner;
        timeRequired = newTimeRequired;
    }
    
    public String getName(){ return name; }
    public String getDetails(){ return details; }
    public ArrayList getProjectItems(){ return projectItems; }
    public Contact getOwner(){ return owner; }
    public double getTimeRequired(){
        double totalTime = timeRequired;
        Iterator items = projectItems.iterator();
        while(items.hasNext()){
            ProjectItem item = (ProjectItem)items.next();
            totalTime += item.getTimeRequired();
        }
        return totalTime;
    }
    
    public void setName(String newName){ name = newName; }
    public void setDetails(String newDetails){ details = newDetails; }
    public void setOwner(Contact newOwner){ owner = newOwner; }
    public void setTimeRequired(double newTimeRequired){ timeRequired = newTimeRequired; }
    
    public void addProjectItem(ProjectItem element){
        if (!projectItems.contains(element)){
            projectItems.add(element);
        }
    }
    public void removeProjectItem(ProjectItem element){
        projectItems.remove(element);
    }
}


           
       
Related examples in the same category
1. Java中复合模式Java中复合模式
2. Java 2 中复合模式Java 2 中复合模式
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.