Chain Pattern : Call Back Pattern « Design Pattern « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Design Pattern » Call Back PatternScreenshots 
Chain Pattern

//[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.io.File;
import java.util.ArrayList;
import java.util.Iterator;
public class RunChainPattern {
    public static void main(String [] arguments){
        System.out.println("Example for the Chain of Responsibility pattern");
        System.out.println();
        System.out.println("This code uses chain of responsibility to obtain");
        System.out.println(" the owner for a particular ProjectItem, and to");
        System.out.println(" build up a list of project details. In each case,");
        System.out.println(" a call to the appropriate getter method, getOwner");
        System.out.println(" or getDetails, will pass the method call up the");
        System.out.println(" project tree.");
        System.out.println("For getOwner, the call will return the first non-null");
        System.out.println(" owner field encountered. For getDetails, the method");
        System.out.println(" will build a series of details, stopping when it");
        System.out.println(" reaches a ProjectItem that is designated as a");
        System.out.println(" primary task.");
        System.out.println();
        
        System.out.println("Deserializing a test Project for Visitor pattern");
        System.out.println();
        if (!(new File("data.ser").exists())){
            DataCreator.serialize("data.ser");
        }
        Project project = (Project)(DataRetriever.deserializeData("data.ser"));
        
        System.out.println("Retrieving Owner and details for each item in the Project");
        System.out.println();
        getItemInfo(project);
    }
    
    private static void getItemInfo(ProjectItem item){
        System.out.println("ProjectItem: " + item);
        System.out.println("  Owner: " + item.getOwner());
        System.out.println("  Details: " + item.getDetails());
        System.out.println();
        if (item.getProjectItems() != null){
            Iterator subElements = item.getProjectItems().iterator();
            while (subElements.hasNext()){
                getItemInfo((ProjectItem)subElements.next());
            }
        }
    }
}
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 Task implements ProjectItem{
    private String name;
    private ArrayList projectItems = new ArrayList();
    private Contact owner;
    private String details;
    private ProjectItem parent;
    private boolean primaryTask;
    
    public Task(ProjectItem newParent){
        this(newParent, """", null, false);
    }
    public Task(ProjectItem newParent, String newName,
        String newDetails, Contact newOwner, boolean newPrimaryTask){
            parent = newParent;
            name = newName;
            owner = newOwner;
            details = newDetails;
            primaryTask = newPrimaryTask;
    }
    
    public Contact getOwner(){
        if (owner == null){
            return parent.getOwner();
        }
        else{
            return owner;
        }
    }
    
    public String getDetails(){
        if (primaryTask){
            return details;
        }
        else{
            return parent.getDetails() + EOL_STRING + "\t" + details;
        }
    }
    
    public String getName(){ return name; }
    public ArrayList getProjectItems(){ return projectItems; }
    public ProjectItem getParent(){ return parent; }
    public boolean isPrimaryTask(){ return primaryTask; }
    
    public void setName(String newName){ name = newName; }
    public void setOwner(Contact newOwner){ owner = newOwner; }
    public void setParent(ProjectItem newParent){ parent = newParent; }
    public void setPrimaryTask(boolean newPrimaryTask){ primaryTask = newPrimaryTask; }
    public void setDetails(String newDetails){ details = newDetails; }
    
    public void addProjectItem(ProjectItem element){
        if (!projectItems.contains(element)){
            projectItems.add(element);
        }
    }
    
    public void removeProjectItem(ProjectItem element){
        projectItems.remove(element);
    }
    
    public String toString(){
        return name;
    }
}

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", contact2);
        
        Task task1 = new Task(project, "Fortune""Acquire a small fortune", contact4, true);
        Task task2 = new Task(project, "Isle""Locate an island for sale", null, true);
        Task task3 = new Task(project, "Name""Decide on a name for the island", contact3, false);
        project.addProjectItem(task1);
        project.addProjectItem(task2);
        project.addProjectItem(task3);
        
        Task task4 = new Task(task1, "Fortune1""Use psychic hotline to predict winning lottery numbers", null, false);
        Task task5 = new Task(task1, "Fortune2""Invest winnings to ensure 50% annual interest", contact1, true);
        Task task6 = new Task(task2, "Isle1""Research whether climate is better in the Atlantic or Pacific", contact1, true);
        Task task7 = new Task(task2, "Isle2""Locate an island for auction on EBay", null, false);
        Task task8 = new Task(task2, "Isle2a""Negotiate for sale of the island", null, false);
        Task task9 = new Task(task3, "Name1""Research every possible name in the world", null, true);
        Task task10 = new Task(task3, "Name2""Eliminate any choices that are not coffee-related", contact4, false);
        task1.addProjectItem(task4);
        task1.addProjectItem(task5);
        task2.addProjectItem(task6);
        task2.addProjectItem(task7);
        task2.addProjectItem(task8);
        task3.addProjectItem(task9);
        task3.addProjectItem(task10);
        return project;
    }
    
    private static void serializeToFile(Serializable content, String fileNamethrows IOException{
        ObjectOutputStream serOut = new ObjectOutputStream(new FileOutputStream(fileName));
        serOut.writeObject(content);
        serOut.close();
    }
}

interface ProjectItem extends Serializable{
    public static final String EOL_STRING = System.getProperty("line.separator");
    public ProjectItem getParent();
    public Contact getOwner();
    public String getDetails();
    public ArrayList getProjectItems();
}

class Project implements ProjectItem{
    private String name;
    private Contact owner;
    private String details;
    private ArrayList projectItems = new ArrayList();
    
    public Project(){ }
    public Project(String newName, String newDetails, Contact newOwner){
        name = newName;
        owner = newOwner;
        details = newDetails;
    }
    
    public String getName(){ return name; }
    public String getDetails(){ return details; }
    public Contact getOwner(){ return owner; }
    public ProjectItem getParent(){ return null}
    public ArrayList getProjectItems(){ return projectItems; }
    
    public void setName(String newName){ name = newName; }
    public void setOwner(Contact newOwner){ owner = newOwner; }
    public void setDetails(String newDetails){ details = newDetails; }
    
    public void addProjectItem(ProjectItem element){
        if (!projectItems.contains(element)){
            projectItems.add(element);
        }
    }
    
    public void removeProjectItem(ProjectItem element){
        projectItems.remove(element);
    }
    
    public String toString(){
        return name;
    }
}

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;
    }
}

           
       
Related examples in the same category
1. Callback Pattern in Java
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.