java4all@1986 java. Powered by Blogger.

What is meant Observer Design Pattern?

>> Friday, May 27, 2011

Observer Design Pattern:
          One object changes state, all of its dependents are updated automatically.

        

Where to use & benefits


  • One change affects one or many objects.
  • Many object behavior depends on one object state.
  • Need broadcast communication.
  • AKA “Publish-Subscribe”.
  • Maintain consistency between objects
  • keep classes from becoming too tightly coupled, which would hamper reusability.
  • Related patterns include 
Example:
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

class DisplayForm extends JFrame {
InputFormObserver input = new InputFormObserver();
InputForm inputForm ;
Observable obsInput;
JTextField display;
//...
public DisplayForm() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
inputForm = new InputForm();
obsInput = inputForm.getInputInfo();
obsInput.addObserver(input);

display = new JTextField(10);
display.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

}
});
getContentPane().add(display);
setTitle("Observer form");
setSize(200,100);
setLocation(200,100);
setVisible(true);

}

private class InputFormObserver implements Observer {
public void update(Observable ob, Object o) {
doSomeUpdate();
if (obsInput.countObservers()>0)
obsInput.deleteObservers();
obsInput = inputForm.getInputInfo();
obsInput.addObserver(input);
}

}
public void doSomeUpdate() {
display.setText(inputForm.getText());
JOptionPane.showMessageDialog(DisplayForm.this,
"This form has been updated");
}
public static void main(String args[]) {
DisplayForm df = new DisplayForm();
}
}
class InputForm extends JFrame {
public InformDisplay inform = new InformDisplay();
//...
JTextField input= new JTextField(10);

public InputForm() {
JPanel panel= new JPanel();
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inform.notifyObservers();
}
});
panel.add(new JLabel("Enter: "));
panel.add(input);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
getContentPane().add(panel);
setTitle("Observable form");
setSize(200,100);
setVisible(true);
}
public Observable getInputInfo() {
return inform;
}

public String getText() {
return input.getText();
}

private class InformDisplay extends Observable {
public void notifyObservers() {
setChanged();
super.notifyObservers();
}
public String getChange() {
return input.getText();
}
}
//...
}

Read more...

What is meant by Template Design Pattern?

TEMPLATE  DESIGN PATTERN:
                Provide an abstract definition for a method or a class and redefine its behavior later or on the fly without changing its structure.


Where to use & benefits


  • To make many similar operations template.
  • From many specialized operations to a generalized operation.
  • Refactor common behavior to simplify code.
  • Algorithm related improvement.
  • Need good coding skill to conquer it.
  • May be hard to read for novice.
  • Easy to produce ambiguity if not written well.
  • Related patterns include 
EXAMPLE:
abstract class CheckBackground {
  
    public abstract void checkBank();
    public abstract void checkCredit();
    public abstract void checkLoan();
    public abstract void checkStock();
    public abstract void checkIncome();

  //work as template method
    public void check() {
        checkBank();
        checkCredit();
        checkLoan();
        checkStock();
        checkIncome(); 
    }
}

class LoanApp extends CheckBackground {
    private String name;
   
    public LoanApp(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

    public void checkBank() {
        //ck acct, balance
        System.out.println("check bank...");
    }

    public void checkCredit() {
        //ck score from 3 companies
        System.out.println("check credit...");
    }

    public void checkLoan() {
        //ck other loan info
        System.out.println("check other loan...");
    }

    public void checkStock() {
        //ck how many stock values
        System.out.println("check stock values...");
    }

    public void checkIncome() {
        //ck how much a family make
        System.out.println("check family income...");
    }
   
    //other methods
}

class TestTemplate {
    public static void main(String[] args) {
        
        LoanApp mortgageClient = new LoanApp("Judy");
        System.out.println("\nCheck client " + mortgageClient.getName()+ " Mortgage loan application. ");
        mortgageClient.check();
        
        LoanApp equityloanClient = new LoanApp("Mark");
        System.out.println("\nCheck client " + equityloanClient.getName()+ " equity loan application. ");
        equityloanClient.check();
    }
}

Read more...

What is meant by Bridge Design Pattern?

BRIDGE DESIGN PATTERN:Decouple an abstraction or interface from its implementation so that the two can vary independently.

  Where to use & benefits

  • Want to separate abstraction and implementation permanently
  • Share an implementation among multiple objects
  • Want to improve extensibility
  • Hide implementation details from clients
  • Related patterns include 
EXAMLPE:



    import java.util.*;
    
    //abstraction
    interface Question {
      
        public void nextQuestion();
        public void priorQuestion();
        public void newQuestion(String q);
        public void deleteQuestion(String q);
        public void displayQuestion();
        public void displayAllQuestions();
    }
    
    //implementation
    class QuestionManager {
     
      protected Question questDB; //instantiate it later 
      public String catalog;
    
      public QuestionManager(String catalog) {
          this.catalog = catalog;
      }
    
      public void next() {
          questDB.nextQuestion();
      }
    
      public void prior() {
          questDB.priorQuestion();
      }
    
      public void newOne(String quest) {
          questDB.newQuestion(quest);
      }
    
      public void delete(String quest) {
          questDB.deleteQuestion(quest);
      }
    
      public void display() {
          questDB.displayQuestion();
      }
    
      public void displayAll() {
          System.out.println("Question Catalog: " + catalog);
          questDB.displayAllQuestions();
      }
    }
    
    
    //further implementation
    class QuestionFormat extends QuestionManager {
      
        public QuestionFormat(String catalog){
            super(catalog);
        }
    
        public void displayAll() {
        
            System.out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~");
            super.displayAll();
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
        }
    }
    
    //decoupled implementation
    class JavaQuestions implements Question {
      
        private List questions = new ArrayList();
        private int current = 0;
    
        public JavaQuestions() {
            //load from a database and fill in the container
            questions.add("What is Java? ");
            questions.add("What is an interface? ");
            questions.add("What is cross-platform? ");
            questions.add("What is UFT-8? ");
            questions.add("What is abstract? ");
            questions.add("What is Thread? ");
            questions.add("What is multi-threading? ");
     
        }
    
        public void nextQuestion() {
            if( current <= questions.size() - 1 )
                current++;
        }
    
        public void priorQuestion() {
            if( current > 0 )
                current--;
        }
    
        public void newQuestion(String quest) {
            questions.add(quest);
        }
    
        public void deleteQuestion(String quest) {
            questions.remove(quest);
        }
    
        public void displayQuestion() {
            System.out.println( questions.get(current) );
        }
    
        public void displayAllQuestions() {
            for (String quest : questions) {
                System.out.println(quest);
            }
        }
    }
    
    
    class TestBridge {
        public static void main(String[] args) {
     
            QuestionFormat questions = new QuestionFormat("Java Language");
    
            questions.questDB = new JavaQuestions();//can be hooked up with other question class
            //questions.questDB = new CsharpQuestions();
            //questions.questDB = new CplusplusQuestions();
    
            questions.display();
            questions.next();
        
            questions.newOne("What is object? ");
            questions.newOne("What is reference type?");
    
            questions.displayAll();
      }
    

    Read more...

    What is meant by Adapater Design Pattern?


    <pre class='brush:Plain Text;'>
     
    
    ADAPATER DESIGN PATTERN:
             Convert the existing interfaces to a new interface to achieve compatibility and reusability of the unrelated classes in one application. Also known as Wrapper pattern.


    Where to use & benefits


    • Try to match an interface(WindowAdapter, etc.)
    • Make unrelated classes work together.
    • Multiple compatibility.
    • Increase transparency of classes.
    • Make a pluggable kit.
    • Delegate objects.
    • Highly class reusable.
    • Achieve the goal by inheritance or by composition
    • Related patterns include

    
    
    </pre>
    
    

    Example

    The famous adapter classes in Java API are WindowAdapter,ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter.
    As you know, WindowListner interface has seven methods. Whenever your class implements such interface, you have to implements all of the seven methods. WindowAdapter class implements WindowListener interface and make seven empty implementation. When you class subclass WindowAdapter class, you may choose the method you want without restrictions. The following give such an example.
    <pre class='brush:Java'>

    public interface Windowlistener {
    public void windowClosed(WindowEvent e);
    public void windowOpened(WindowEvent e);
    public void windowIconified(WindowEvent e);
    public void windowDeiconified(WindowEvent e);
    public void windowActivated(WindowEvent e);
    public void windowDeactivated(WindowEvent e);
    public void windowClosing(WindowEvent e);
    }
    public class WindowAdapter implements WindowListner{
    public void windowClosed(WindowEvent e){}
    public void windowOpened(WindowEvent e){}
    public void windowIconified(WindowEvent e){}
    public void windowDeiconified(WindowEvent e){}
    public void windowActivated(WindowEvent e){}
    public void windowDeactivated(WindowEvent e){}
    public void windowClosing(WindowEvent e){}
    }
    Here is a test program
    import javax.swing.*;
    import java.awt.event.*;
    class Test extends JFrame {
    public Test () {
    setSize(200,200);
    setVisible(true);
    addWindowListener(new Closer());
    }
    public static void main(String[] args)
    {
    new Test();
    }
    class Closer extends WindowAdapter {
    public void windowClosing(WindowEvent e)
    {
    System.exit(0);
    }
    }
    }
    To reuse classes and make new class compatible with existing ones. For example, A clean system is already designed, you want to add more job in, the Extra interface uses adapter pattern to plug in the existing system.
    interface Clean {
    public void makeClean();
    }
    class Office implements Clean{
    public void makeClean()
    {
    System.out.println("Clean Office");
    }
    }
    class Workshop implements Clean{ public void makeClean() {
    System.out.println("Clean Workshop");
    }
    }
    interface Extra extends Clean{
    public void takeCare();
    }
    class Facility implements Extra{
    public void makeClean()
    {
    System.out.println("Clean Facility");
    }
    public void takeCare()
    {
    System.out.println("Care has been taken");
    }
    }
    In order to reuse Workshop and Office classes, we create an adapter interface Extra and add new job takeCare in the system. class Test
    {
    static void Jobs (Extra job)
    { if(job instanceof Clean)
    ((Clean)job).makeClean();
    if (job instanceof Extra)
    ((Extra)job).takeCare();
    }
    public static void main(String[] args)
    {
    Extra e = new Facility();
    Jobs(e);
    Clean c1 = new Office();
    Clean c2 = new Workshop();
    c1.makeClean();
    c2.makeClean();
    e.makeClean();
    }
    }
     
     </pre>

    Read more...

    What is meant by Composite Design Pattern?

    COMPOSITE:
               Build a complex object out of elemental objects and itself like a tree structure.

     

    Where to use & benefits


    • Want to represent a part-whole relationship like tree folder system
    • Group components to form larger components, which in turn can be grouped to form still larger components.
    • Related patterns include 

    Example

    A component has many elements and itself which has many elements and itself, etc. A file system is a typical example. Directory is a composite pattern. When you deal with Directory object, if isFile() returns true, work on file, if isDirectory() returns true, work on Directory object.
    class Directory {
       Directory dir;
       File[] f;
       ...
       
       boolean isDirectory() {
           return f == null;
       }
       boolean isFile() {
           return f != null;
       }
       File getFile(int i) {
          if (isFile())
             return f[i];
          return null'
       }
       Directory getDirectory() {
          if (isDirectory())
              return dir;
          return null;
       }
       ....
    }
    

    Read more...

    What is meant Facade Design Pattern?

    FACADE DESIGN PATTERN:
       It comes under Structural Design Pattern.Make a complex system simpler by providing a unified or general interface, which is a higher layer to these subsystems.


    Where to use & benefits


    • Want to reduce complexities of a system.
    • Decouple subsystems , reduce its dependency, and improve portability.
    • Make an entry point to your subsystems.
    • Minimize the communication and dependency between subsystems.
    • Security and performance consideration.
    • Shield clients from subsystem components.
    • Simplify generosity to specification.
    • Related patterns include 

    Example

    JDBC design is a good example of Façade pattern. A database design is complicated. JDBC is used to connect the database and manipulate data without exposing details to the clients.
    Security of a system may be designed with Façade pattern. Clients' authorization to access information may be classified. General users may be allowed to access general information; special guests may be allowed to access more information; administrators and executives may be allowed to access the most important information. These subsystems may be generalized by one interface. The identified users may be directed to the related subsystems.
    interface General {
        public void accessGeneral();
    }
    interface Special extends General {
        public void accessSpecial();
    }
    interface Private extends General {
        public void accessPrivate();
    }
    
    class GeneralInfo implements General {
        public void accessGeneral() {
     //...
        }
        //...
    }
    class SpecialInfo implements Special{
        public void accessSpecial() {
            //...
        }
        public void accessGeneral() {}
        //...
    }
    class PrivateInfo implements Private, Special {
        public void accessPrivate() {
     // ...
        }
        public void accessSpecial() {
     //...
        }
        public void accessGeneral() {
     // ...
        }
        //...
    }
    
    class Connection {
       //...
        
       if (user is unauthorized) throw new Exception();
       if (user is general) return new GeneralInfo();
       if (user is special) return new SpecialInfo();
       if (user is executive) return new PrivateInfo();
       //...
    }
    
    The above code example illustrates that the whole system is not exposed to the clients. It depends on the user classification.




    Read more...

    What is meant by REST(Representational State Transfer)

    REST(Representational State Transfer)
          Representational State Transfer (REST) is a Web service design pattern. It is different from SOAP based web services. REST services do not require XML, SOAP or WSDL service-API definitions. The concept originally comes from a PhD's dissertation

       

    Where to use & benefits

    • Can be used for any system design.
    • Basic elements: Resources, URL and simple operations.
    • Resources may be web site, an HTML page, an XML document, a web service, a physical device, etc.
    • Any resource can be identified by URL.
    • Simple operations via HTTP API (GET,POST,PUT,DELETE).
    • Easy to understand each service does by examing the URL.
    • No rules, no bottleneck, no central point of failure.
    • Easy to implement.
    CRUD: 
    
    GET = "give me some info" (Retrieve)
    POST = "here's some update info" (Update)
    PUT = "here's some new info" (Create)
    DELETE = "delete some info" (Delete)
    
    payload: form data
    

    Read more...

    What is meant by Singleton Pattern?

    SINGLETON:
                           One instance of a class or one value accessible globally in an application. 


    Where to use & benefits



    For example, to use a static variable to control the instance;
    class Connection {
        public static boolean haveOne = false;
        public Connection() throws Exception{
            if (!haveOne) {
               doSomething();
               haveOne = true;
            }else {
              throw new Exception("You cannot have a second instance");
            }
        }
        public static Connection getConnection() throws Exception{
            return new Connection();
        }
        void doSomething() {}
        //...
        public static void main(String [] args) {
            try {
                Connection con = new Connection(); //ok
            }catch(Exception e) {
                System.out.println("first: " +e.getMessage());
            }
            try {
                Connection con2 = Connection.getConnection(); //failed.
            }catch(Exception e) {
                System.out.println("second: " +e.getMessage());
            }
        }
    }
    

    Read more...

    What is meant By Factory Pattern?

    FACTORY PATTERN:
                       Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.


    Where to use & benefits



    Examples

    To illustrate such concept, let's use a simple example. To paint a picture, you may need several steps. A shape is an interface. Several implementing classes may be designed in the following way.
    interface Shape {
       public void draw();
    }
    class Line implements Shape {
        Point x, y;
        Line(Point a, Point b) {
           x = a;
           y = b;
        }
        public void draw() {
           //draw a line; 
        }
    }
    class Square implements Shape {
        Point start;
        int width, height;
        Square(Point s, int w, int h) {
            start = s;
            width = w;
            height = h;
        }
        public void draw() {
           //draw a square;
        }
    }
    class Circle implements Shape {
        ....
    }
    
    class Painting {
       Point x, y;
       int width, height, radius;
       Painting(Point a, Point b, int w, int h, int r) {
           x = a;
           y = b;
           width = w;
           height = h;
           radius = r;
       }
       Shape drawLine() {
           return new Line(x,y);
       }
       Shape drawSquare() {
           return new Square(x, width, height);
       }
       Shape drawCircle() {
           return new Circle(x, radius);
       }
       ....
    }
    
    ...
    Shape pic;
    Painting pt;
    //initializing pt 
    ....
    if (line) 
       pic = pt.drawLine();
    if (square)
       pic = pt.drawSquare();
    if (circle)
       pic = pt.drawCircle();
    
    
     From the above example, you may see that the Shape pic's type depends on the condition given. The variable pic may be a line or square or a circle.

    Read more...

    What is meant By Abstract Design Pattern?

    Abstract Factory  :Provides one level of interface higher than the factory pattern. It is used to return one of several factories.

    Where to use & benefits

    • Creates families of related or dependent objects like Kit.
    • Provides a class library of products, exposing interface not implementation.
    • Needs to isolate concrete classes from their super classes.
    • A system needs independent of how its products are created, composed, and represented.
    • Try to enforce a constraint.
    • An alternative to Facade to hide platform-specific classes
    • Easily extensible to a system or a family
    • Related patterns include 

    Example

    Suppose you need to write a program to show data in two different places. Let's say from a local or a remote database. You need to make a connection to a database before working on the data. In this case, you have two choices, local or remote. You may use abstract factory design pattern to design the interface in the following way:

    class DataInfo {}
    interface Local {
      DataInfo[] loadDB(String filename);
    }
    
    interface Remote extends Local{
      void connect2WWW(String url);
    }
    
    class LocalMode implements Local {
      public DataInfo[] loadDB(String name) {
        System.out.print("Load from a local database ");
        return null;
      }
    }
    
    class RemoteMode implements Remote {
      public void connect2WWW(String url) {
        System.out.println("Connect to a remote site ");
      }
      public DataInfo[] loadDB(String name) {
         System.out.println("Load from a remote database ");
         return null;
      }
    }
    
    // The Abstract Factory
    interface ConnectionFactory {
      Local getLocalConnection();
      Remote getRemoteConnection();
    }
    
    class DataManager implements ConnectionFactory {
        boolean local = false;
        DataInfo[] data;
        //...
        public Local getLocalConnection() {
            return new LocalMode();
        }
        public Remote getRemoteConnection() {
            return new RemoteMode();
        }
        public  void loadData() {
             if(local){
                Local conn = getLocalConnection();
                data = conn.loadDB("db.db");
             }else {
                Remote conn = getRemoteConnection();
                conn.connect2WWW("www.some.where.com");
                data = conn.loadDB("db.db");
             }
             
         }
      // work on data 
       
        public void setConnection(boolean b) {
           local = b;
        }
    }
    
    //Use the following Test class to test the above classes
    class Test {
        public static void main(String[] args) {
            DataManager dm = new DataManager();
            DataInfo[] di = null;
            String dbFileName = "db.db";
            if (args.length == 1) {
                //assume local is set to true
         dm.setConnection(true);
                LocalMode lm = (LocalMode)dm.getLocalConnection(); 
         di = lm.loadDB(dbFileName); 
            } else {  
               //Note: dm.local = false is default setting
               RemoteMode rm = (RemoteMode)dm.getRemoteConnection();
               rm.connect2WWW("www.javacamp.org/db/");
               di = rm.loadDB(dbFileName); 
            }
            //use one set of methods to deal with loaded data.
            //You don't need to worry about connection from this point.
            //Like di.find(), di.search() etc.
        }
    }


     

                                        

                             

     

      

    Read more...

    Dsign Patterns in J2EE?

    There are n.o of design patterns in Java.Mostly we are using eight Design Patterns in Our application.

    • Business Delegate
    • Composite Entity
    • Data Access Object
    • Front Controller
    • Data Transfer Object
    • Service Locator
    • Intercepting Filter
    • MVC
    1. Business Delegate:
    An intermediate class decouples between presentation-tier clients and business services. 


    Where to use & benefits 


    • Simplify the complicated relationship.
    • Reduce coupling.
    • Cache results and references to remote business services.
    • Cut potentially costly round trips
    • Hide the underlying implementation details of business service.
    • Related patterns include.

    Composite Entity:
    Use a coarse-grained interface to manage interactions between fine-grained or coarse-grained and dependent objects internally. The Composite Entity is a coarse-grained entity bean. It may be the coarse-grained object or hold a reference to the coarse-grained object. Also known as Aggregate Entity. 


    Where to use & benefits  


    • Combine coarse-grained object and its related dependent objects into a single entity bean.
    • Multiple clients share persistent objects.
    • Model a network of related business entities.
    • In both local and distributed environment, use remote entity beans to model dependent business objects or fine-grained objects.
    • Improve performance by eliminating the parameter and return value serialization and data transmission costs.
    • Eliminate inter-entity relationships
    • Improve manageability by reducing entity beans.
    • Improve network performance
    • Reduce database schema dependency 
    Data Access Object :
    Adapt a uniform interface to access multiple databases like relational, unrelational, object-oriented, etc.


    Where to use & benefits 


    • Need to access multiple data sources like legacy systems, B2B, LDAP, and so forth.
    • Lack of uniform APIs to address the requirements to access disparate systems.
    • Persistent storage APIs vary depending on the product vendor.
    • Adapt and encapsulate all access to the data source.
    • Hide the data source implementation details from its clients.
    • More portable and less code dependencies in components.
    • Solve differences in the APIs which is used to access different persistent storage mechanisms.
    • Not useful for container-managed persistence.
    Front Controller:
    Using a single component to process application requests.


    Where to use & benefits 


    • JSP or Servlet.
    • Design request handling component.
    • Channel all requests through a single controller.
    • Centralize request processing and view selection.
    • Reduce business logic in a view
    • Improve manageability of security
    • Promote code reuse across requests
    • Avoid code duplication
    • Related patterns include 
    Data Transfer Object :

    Using a serializable class to act as data carrier, grouping related attributes, forming a composite value and working as a return type from remote business method. Also known as Value object.


     Where to use & benefits 

    • Get related values from remote business method.
    • Fetch multiple values in one trip.
    • Decrease network traffic.
    • Minimize latency and server resource usage.
    • Related patterns include 
    ServiceLocator:
    Centralizing distributed service object lookups, providing a centralized point of control, acting as a cache that eliminates redundant lookups.

     Where to use & benefits 

    • Lookup object in JNDI, RMI, JMS, etc.
    • Encapsulate any vendor-specific features of lookup process
    • Simplify the lookup process
    • Improve the performance
    • Related patterns include 
     Intercepting Filter:
    A pluggable component design to intercept incoming requests and outgoing responses, provide common services in a standard manner (independently) without changing core processing code.

     Where to use & benefits

    • Logging and authentication.
    • Enhance security.
    • Add additional function to existing web application.
    • Decorate main process.
    • Debug.
    • Pre-processing or post-processing for specific clients.
    • Uncompress incoming request.
    • Convert input encoding schema.
    • Being added or removed transparently or declaratively and triggered automatically
    • Improve reusability 
    MVC:
    The Model/View/Controller(MVC) is an architecture design pattern. Model means data, View means representation and Controller works on data and representation. MVC focuses on decouple the triad relationships among data, representation and controller.

     Where to use & benefits

    • Application architecture design.
    • Any data related design, including non-visual application.
    • Decouple complex object to improve maintainability.
    • Increase object reusability.
    • Achieve design flexibility.
    • Related patterns include 








    Read more...

    FaceBook Login

    HTML/JAVASCRIPT

    HTML/JAVASCRIPT

    HTML/JAVASCRIPT

    HTML/JAVASCRIPT

    Total Pageviews

    STATCOUNTER

      © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

    Back to TOP