Sie sind auf Seite 1von 14

Java/J2EE Design Pattern

Java Design Patterns


ARUMUGA BABU K
EMP ID: 362 102

Java/J2EE Design Pattern


Java Design Pattern

What is the design pattern? If a problem occurs over and over again, a solution to that problem has been used effectively. That solution is described as a pattern. The design patterns are languageindependent strategies for solving common object-oriented design problems. When you make a design, you should know the names of some common solutions. Learning design patterns is good for people to communicate each other effectively. In fact, you may have been familiar with some design patterns, you may not use well-known names to describe them. SUN suggests GOF (Gang Of Four--four pioneer guys who wrote a book named "Design Patterns"- Elements of Reusable Object-Oriented Software), so we use that book as our guide to describe solutions. Please make you be familiar with these terms and learn how other people solve the code problems. How many design patterns? Many. A site says at least 250 existing patterns are used in OO world, including Spaghetti which refers to poor coding habits. The 23 design patterns by GOF are well known, and more are to be discovered on the way. Note that the design patterns are not idioms or algorithms or components. What is the relationship among these patterns? Generally, to build a system, you may need many patterns to fit together. Different designer may use different patterns to solve the same problem. Usually:

Some patterns naturally fit together One pattern may lead to another Some patterns are similar and alternative Patterns are discoverable and documentable Patterns are not methods or framework Patterns give you hint to solve a problem effectively

Java/J2EE Design Pattern


Behavioral Patterns Command Design Pattern Command design pattern is used to encapsulate a request as an object and pass to an invoker, wherein the invoker does not knows how to service the request but uses the encapsulated command to perform an action. To understand command design pattern we should understand the associated key terms like client, command, command implementation, invoker, receiver.

Command is an interface with execute method. It is the core of contract. A client creates an instance of a command implementation and associates it with a receiver. An invoker instructs the command to perform an action. A Command implementations instance creates a binding between the receiver and an action. Receiver is the object that knows the actual steps to perform the action. Command Pattern Discussion

It will be easier to understand all the above with an example. Let us think of developing a universal remote. Our UnversalRemote will have only two buttons, one is to power on and another is to mute all associated ConsumerElectronics. For ConsumerElectronics we will have couple of implementations Television and SoundSystem. Button is a class that is the invoker of an action. OnCommand is used to switch on a ConsumerElectronics. While instantaiting OnCommand client needs to set the receiver. Here receiver is either Television or SoundSystem. UniversalRemote class will maintain all the receivers and will provide a method to identify the currently active receiver. When an instance of a invoker is created, a concrete command is passed to it. Invoker does not know how to perform an action. All it does is honoring the agreement with the Command. Invoker calls the execute() method of the set concrete command.

Java/J2EE Design Pattern


UML Diagram for Command Pattern

Command Pattern Example Implementation Command.java package com.javapapers.designpattern.command; public interface Command { public abstract void execute(); } OnCommand.java package com.javapapers.designpattern.command; public class OnCommand implements Command { private ConsumerElectronics ce; public OnCommand(ConsumerElectronics ce) { this.ce = ce; }

Java/J2EE Design Pattern


public void execute() { ce.on(); } } MuteAllCommand.java package com.javapapers.designpattern.command; import java.util.List; public class MuteAllCommand implements Command { List<ConsumerElectronics> ceList; public MuteAllCommand(List<ConsumerElectronics> ceList) { this.ceList = ceList; } @Override public void execute() { for (ConsumerElectronics ce : ceList) { ce.mute(); } } } ConsumerElectronics.java package com.javapapers.designpattern.command; public interface ConsumerElectronics { public abstract void on(); public abstract void mute(); } Television.java package com.javapapers.designpattern.command; public class Television implements ConsumerElectronics { public void on() { System.out.println("Television is on!"); } @Override public void mute() {

Java/J2EE Design Pattern


System.out.println("Television is muted!"); } } SoundSystem.java package com.javapapers.designpattern.command; public class SoundSystem implements ConsumerElectronics { public void on() { System.out.println("Sound system is on!"); } @Override public void mute() { System.out.println("Sound system is muted!"); } } Button.java package com.javapapers.designpattern.command; public class Button { Command c; public Button(Command c) { this.c = c; } public void click(){ c.execute(); } } UniversalRemote.java package com.javapapers.designpattern.command; public class UniversalRemote { public static ConsumerElectronics getActiveDevice() { // here we will have a complex electronic circuit :-) // that will maintain current device Television tv = new Television(); return tv;

Java/J2EE Design Pattern


} } DemoCommandPattern.java package com.javapapers.designpattern.command; import java.util.ArrayList; import java.util.List; public class DemoCommandPattern { public static void main(String args[]) { // OnCommand is instantiated based on active device supplied by Remote ConsumerElectronics ce = UniversalRemote.getActiveDevice(); OnCommand onCommand = new OnCommand(ce); Button onButton = new Button(onCommand); onButton.click(); Television tv = new Television(); SoundSystem ss = new SoundSystem(); List<ConsumerElectronics> all = new ArrayList<ConsumerElectronics>(); all.add(tv); all.add(ss); MuteAllCommand muteAll = new MuteAllCommand(all); Button muteAllButton = new Button(muteAll); muteAllButton.click(); } }

Important Points on Command Pattern


Command pattern helps to decouple the invoker and the receiver. Receiver is the one which knows how to perform an action. Command helps to implement call back in java. Helps in terms of extensibility as we can add new command without changing existing code. Command defines the binding between receiver and action. A command should be able to implement undo and redo operations. That is resting the state of the receiver. It can be done from the support of receiver.

Java/J2EE Design Pattern

J2EE Patterns MVC

Definition 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 o Almost all patterns can be used with MVC.

History The Model/View/Controller(MVC) originates from Smalltalk, an OO programming language. Core issue MVC consists of three kind of objects. The Model is an internal representation of the data, the View is the screen presentation of GUI, and the Controller coordinates changes between the Model and View. SCJD project design To achieve the MVC architecture in your project, you have to decouple View and Model by Controller. Your GUI as View should be designed as a module. It can be launched separately. Your data related classes as Model should be treated as a module too. Your controller classes should response to any data change on the GUI. Such design will increase reusability and flexibility.

Java/J2EE Design Pattern


Try to visualize that the user reacts with the GUI, a DataManager(Controller) listens to the GUI's call. If the user needs to load data, such request is sent to the DataManager, the DataManager starts loading, searching and extracting the requested data from the server and sends it back to the GUI. GUI is responsible to display data. Here the server acts as Model, the DataManager acts as Controller and GUI acts as View. The DataManager can be used for both remote and local modes (design two constructors for both modes), the GUI can be replaced with any design and the data related classes can be packaged together and put on local and server sides. All of the three objects can be reused for other projects with little code alteration. If you grasp such concept and skill, you will save a lot of time in designing and developing your projects in the future. This is the so-called OOA/OOD. Composite Design Pattern When we want to represent part-whole hierarchy, use tree structure and compose objects. We know tree structure what a tree structure is and some of us dont know what a partwhole hierarchy is. A system consists of subsystems or components. Components can further be divided into smaller components. Further smaller components can be divided into smaller elements. This is a part-whole hierarchy. Everything around us can be a candidate for part-whole hierarchy. Human body, a car, a computer, lego structure, etc. A car is made up of engine, tyre, Engine is made up of electrical components, valves, Electrical components is made up of chips, transistor, Like this a component is part of a whole system. This hierarchy can be represented as a tree structure using composite design pattern

. Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. is the intent by GoF.

Java/J2EE Design Pattern

Real World Example In this article, let us take a real world example of part-whole hierarchy and use composite design pattern using java. As a kid, I have spent huge amount of time with lego building blocks. Last week I bought my son an assorted kit lego and we spent the whole weekend together building structures. Let us consider the game of building blocks to practice composite pattern. Assume that our kit has only three unique pieces ( 1, 2 and 4 blocks) and let us call these as primitive blocks as they will be the end nodes in the tree structure. Objective is to build a house and it will be a step by step process. First using primitive blocks, we should construct multiple windows, doors, walls, floor and let us call these structures. Then use all these structure to create a house.

Primitive blocks combined together gives a structure. Multiple structures assembled together gives a house. Important Points

Importance of composite pattern is, the group of objects should be treated similarly as a single object. Manipulating a single object should be as similar to manipulating a group of objects. In sync with our example, we join primitive blocks to create structures and similarly join structures to create house. Recursive formation and tree structure for composite should be noted. Clients access the whole hierarchy through the components and they are not aware about if they are dealing with leaf or composites.

Java/J2EE Design Pattern


Tree for Composite When we get a recursive structure the obvious choice for implementation is a tree. In composite design pattern, the part-whole hierarchy can be represented as a tree. Leaves (end nodes) of a tree being the primitive elements and the tree being the composite structure.

Uml Design for Composite Pattern Component: (structure) 1. Component is at the top of hierarchy. It is an abstraction for the composite. 2. It declares the interface for objects in composition. 3. (optional) defines an interface for accessing a components parent in the recursive structure, and implements it if thats appropriate. Leaf: (primitive blocks) 1. The end nodes of the tree and will not have any child. 2. Defines the behaviour for single objects in the composition Composite: (group) 1. Consists of child components and defines behaviour for them 2. Implements the child related operations.

Java/J2EE Design Pattern

Composite Pattern Implementation package com.javapapers.designpattern.composite; public class Block implements Group { public void assemble() { System.out.println("Block"); } } package com.javapapers.designpattern.composite; public interface Group { public void assemble(); } package com.javapapers.designpattern.composite; import java.util.ArrayList; import java.util.List; public class Structure implements Group { // Collection of child groups. private List<Group> groups = new ArrayList<Group>(); public void assemble() { for (Group group : groups) { group.assemble(); }

Java/J2EE Design Pattern


} // Adds the group to the structure. public void add(Group group) { groups.add(group); } // Removes the group from the structure. public void remove(Group group) { groups.remove(group); } } package com.javapapers.designpattern.composite; public class ImplementComposite { public static void main(String[] args) { //Initialize three blocks Block block1 = new Block(); Block block2 = new Block(); Block block3 = new Block(); //Initialize three structure Structure structure = new Structure(); Structure structure1 = new Structure(); Structure structure2 = new Structure(); //Composes the groups structure1.add(block1); structure1.add(block2); structure2.add(block3); structure.add(structure1); structure.add(structure2); structure.assemble(); } } Usage of Composite Design Pattern in Sun/Oracle JDK

java.awt.Container#add(Component) in awt, we have containers and components a classic implementation javax.faces.component.UIComponent#getChildren()

Java/J2EE Design Pattern

Thank You
ARUMUGA BABU K
EMP ID: 362 102

Das könnte Ihnen auch gefallen