Sunday, September 28, 2008

Structural Patterns - Adapter, Decorator, Composite, etc.


Structural Design Patterns - Adapter, Decorator, Composite, etc.

Want to refresh your understanding of Design Patterns, its types, usability, etc. first then you may like to refer to this article - Design Patterns >>

Structural Design Patterns

Design Patterns belonging to this category are used to combine classes and objects to form larger structures to suit your requirements. How do we actually achieve this? Class based structural design patterns use Inheritance to form larger structures whereas Object based structural design patterns use Composition for the same. The most popular structural design patterns are The Adapter Design Pattern, The Decorator Design Pattern, The Bridge Design Pattern, The Composite Design Pattern, The Proxy Design Pattern, The Facade Design Pattern, and The Flyweight Design Pattern.

We'll see Adapter, Decorator, and Composite Design Patterns in this article and discuss the other structural design patterns in subsequent articles. In this article we'll also see how the three design patterns (which look to be very similar) - Adapter, Decorator, and Composite differ from each other.

Adapter Design Pattern

As the name might suggest this design pattern is used where an unrelated class having a different interface is required to accept calls to the methods which are actually part of some other class having a different interface. How to do it? Well... there are the same two ways which we discussed above - using Interfaces and Composition. Suppose we have two classes A and B where we would like to have an instance of the type A to accept calls to the methods of class B then using inheritance we can derive a sub-class (say C) from A and add those methods of Class B into the new sub-class C so that they can be called on an instance of class C which will of course be of type A. Using composition we can simply have a new class which will have the original non-compliant class as a member and we'll add the required methods in this new class to internally call the corresponding methods of the non-compliant member class.

Example: Adapter Using Inheritance

class A{

public void methodA(int a){
...
}

...

}

class B{

public void methodB(){
...
}

...

}

class C extends class A{

public void methodB(){

...

int intValue = 5; //compute the actual int value

methodA(intValue);

}

...

}

Example: Adapter Using Composition

class A{

public void methodA(int a){
...
}

...

}

class B{

public void methodB(){
...
}

...

}

class C{

private A objectRefA;
...

public void methodB(){

int intValue = 5; //compute the actual int value

objectRefA.methodA(intValue);

}

...

}

Decorator Design Pattern

This design pattern is used to decorate the behavior of individual objects of a class without having to create a new derived class. It's normally used in UI design. Suppose there is a requirement where some of the instances of an UI component need a differnt look and feel (maybe based on the section of the screen they appear at or due to any other possible reason) then in such a case creating those many position-based derived classes of that UI component doesn't seem to be a good idea. Instead we can have a Decorator class having the basic look and feel and from it we can derive classed which will render those specific position-based look and feel. This will make the UI design more flexible by separating the actual UI component with its position-dependent look-n-feel. The same UI component can be used for all its occurrences with the corresponding decorator classes. Here the decorator classes will contain the actual UI component as a member and apply the area/position based look-n-feel logic on the contained instance(s).

class UIComp1{
...
}

class Decorator{

//...basic decoration of components
...

}

class DecoratorUIComp1Header extends Decorator{

//...Header specific decoration for UIComp1
...

}


Composite Design Pattern

This design pattern is used to make a composite of several primitive or composite member objects to have a common class which can accept calls intended to a variety of specialized objects (or cases). The composite children are normally termed as nodes and the primitives are called leaves. Example: suppose we need a common method which returns the specialized technical skills of an employee and all of its reportees (if the employee has any) then the Employee class may have a data structure (say a Vector) to store all the reportees which will themselves be instances of the Employee class only. Now we can have a common method getExpertise which will club the skills of the Employee which those of the reportees (if any) and return the clubbed data.

class Employee{

...
private String skill;
private Vector reportees;
...

public String getExpertise(){

String expertise = skill;

for(int i = 0; i < reportees.length; ++i)
expertise += ((Employee)reportees.elementAt(i)).getExpertise();

return expertise;
}

...

}

How do Adapters, Decorators and Composites differ?

Adapters may seem to decorate, but they are primarily used for enabling a class to accept calls belonging to a different interface. We have already sen above how inheritance and composition can be used to achieve this.

Decorators are not used to add different methods to all the instances instead they are used to add specific behavior to some specific instances. Though Adapters making use of composition may also be used here, but the intention is different here with what it's in case of a Adapter.

As discussed above, Composites are mainly used to provide a single interface to multiple instances which internally may have different structures depending on the values of the composed members in each of these instances. In the example discussed above we see that every Employee instance will invoke the same method 'getExpertise()' irespective of whether the instance represents a Employee having no reportees or the one who is having reportees (each of these reportees may themselves have their own reportees).

Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Monday, September 22, 2008

Creating zip/jar files programmatically in Java


Creating zip/jar files programmatically in Java

Write a Java application which automatically zips the directories. The application should accept the input and output directories specified either through command prompt or via a properties file. The user should be able to specify From Date and To Date if s/he wishes so that only those directories in the specified input directory which have their last modified date in that range get zipped.


public class CreateZip{

private static FileOutputStream fos = null;
private static ZipOutputStream zos = null;
private static int BUFFER = 2048;
private static String inputDir = "C:\\input";
private static String outputDir = "C:\\output";
private static Date fromDate = null;
private static Date toDate = null;
private static boolean ZIP_ALL = false;

public CreateZip(){
}

public static void checkDirectories(){

File inputDirectory = new File(getInputDir());
File[] dirList = null;

if(inputDirectory.exist())
if(inputDirectory.isDirectory()){
dirList = inputDirectory.listFiles();
int len = dirList.length;

for(int i = 0; i< dir =" dirList[i];" lastmodified =" dir.lastModified();"> fromDate.getTime()
|| lastModified == fromDate.getTime())
&& (lastModified < lastmodified ="=" filelist =" dir.listFiles();" nooffiles =" fileList.length;" nooffiles ="=" zipfilename =" getOutputDir()" fos =" new" zos =" new" i =" 0;" fis =" new" bis =" new" zipentry =" new" data =" new" bytecount =" bis.read(data,"> -1){
zos.write(data, 0, byteCount);
}
System.out.println(filePath + " added");
} catch(Exception e){
System.out.println("Exception thrown while reading the file: " + e);
System.exit(1);
}
}

public static void main(String[] args){
if(args.length == 0)
setZIP_ALL(true);
else if(args.length == 2){
setInputDir(args[0]);
setOutputDir(args[1]);
}
else if(args.length == 4){
setInputDir(args[0]);
setOutputDir(args[1]);

//... using deprecated method just for testing
setFromDate(new Date(args[2]);
setToDate(new Date(args[3]);
}
else{
System.out.println("Incorrect Usage!");
System.exit(1);
}

System.out.println("Starting the zipping process...");
CreateZip.checkDirectories();
System.out.println("Completed the zipping process!");
}

//... getters and setters of the fields
...




This draft version of the application is just to give you an idea of how easily can you write a Java application to automate the zipping process.

Similarly, you can create JAR file automatically using an almost identical Java program. You just need to change 'ZipOutputStream' with 'JarOutputStream', 'ZipEntry' with 'JarEntry' and probably you're done! Just try out in case you find it interesting.

Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Sunday, September 21, 2008

Differences between Swing and AWT. When to use what?


Differences between Swing and AWT. When to use what?


"Swing" was actually the code name used by Sun during the development and it was planned that on release the extension will be known as JFC (Java Foundation Classes), but Swing managed to beat JFC in popularity even after the release of the package.


Swing package can be used with Java 1.1 as well. For that we need to include three JARs - swing.jar, swingall.jar, windows.jar in the CLASSPATH and the packages are named 'com.sun.java.swing.*', 'com.sun.java.swing.event.*', etc. In Java 1.2 the package names changed to 'javax.swing.*', 'javax.swing.event.*', etc. as the concept of extensions were introduced in Java 1.2 (Java 2 Platform).


Main Differences between Swing and AWT


Swing comonents are light-weight as compared to AWT components for the simple reason that they don't make use of the native UI components of the underlying platform.


Swing components haven been written completely in Java language. Not the same with AWT as it uses native libraries.


Swing components use relatively less number of classes as compared to AWT components not only because the it doesn't depend on native code, but also because it has a better design due to its evolution from AWT. Most of the design flaws got fixed which ultimately led to lesser redundancies.


The look and feel of the Swing components is defined only by the Swing extension classes and it's pluggable to have the look and feel of the underlying platform as well whereas the look and feel of the AWT comonents is mostly goverened by the underlying platform. By default, Swing components open up in their own look and feel.


Swing extension is completely based on the MVC (Model View Controller) architecture and hence the inherent benefits of the MVC design pattern add more value to the usage of Swing.


In addition there are few other trivial differences as well. For example: Swing extension has a richer set of components as compared to AWT, Swing's JPanel automatically gets double buffered and gets repainted faster, etc.


When to use what?


Due to all these advantages, Swing has almost entirely relaced AWT and you got to have a really strong reason if you are still using AWT in your application which is very hard to find at least for platform-independent applications.


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Monday, September 15, 2008

Creational Patterns contd. - Builder & Prototype


Creational Patterns contd. - Builder Design Pattern & Prototype Design Pattern


Builder Design Pattern - this design pattern is used for building a different set of objects based on some passed parameters. We already know that Factory Pattern also does a similar thing, so why to have a different design pattern. Well... Factory Pattern is used to return objects of different type (descendents of a common base class) based on passed parameters, but here we build a set of objects and not just return a descendant object. Got the point?


Let's take an example to understand it better. Suppose you have some data (let's say a table) which you would like to be shown using different graph types based on how many records the table has. For instance, if the number of records are less than 5 then you would like to have a pie-chart otherwise a bar-chart. In such a case this design pattern suggests you to have an abstract class representing the base data (the records to be shown in our case, say in form of Vector or some other suitable collection). You can now derive that abstract class into two concrete classes - PieDisplay and BarDisplay and now one of these two concrete classes can be chosen inside a DisplayFactory class depending upon whether the number of records.


abstract class DisplayRecords{

private Vector recordsToDisplay;

public DisplayRecords(Vector records){

recordsToDisplay = records; }

abstract public Panel display();

...

...

}


class PieDisplay extends DisplayRecords{

...

public PieDisplay(Vector records){

super(records); }

public Panel display(){

//... implementation of pie graph display

... }

...

}


class BarDisplay extends DisplayRecords{

...

public BarDisplay(Vector records){

super(records); }

public Panel display(){

//... implementation of bar graph display

... }

...

}


//...Factory class to make a choice

class DisplayFactory{

...

private DisplayRecords displayRecords;

public DisplayRecords getDisplay(Vector records){

//...building the display

if(records.size() <=5 )

displayRecords = new PieDisplay(records);

else displayRecords = new BarDisplay(records);

return displayRecords;}

...

}



Prototype Design Pattern - this design pattern is used in cases where the instance creation of the class is very complex and/or time consuming so instead of creating new objects everytime we copy the already existing original instance and modify the properties of that instance as required. For example: suppose you have created an object by executing many time consuming database queries and if the new objects can be constructed by modifying the queried data (especially in the cases where you read the DB to create various kind of reports) then you would certainly not like to fire all the queries all over again to create new objects. Instead copying the original instance and modifying the copied data to suit the requirements of the new report will be a better option here.


How to copy an alraedy existing instance? You can use clone method to do that for you. Not sure how to use Cloning? Read this article to have a understanding of what Cloning is all about and how can you implement Shallow Cloning and Deep Cloning - Cloning in Java >>


The limitations of this design pattern is that you may come across some classes where you may not implement cloning - for instance, if the classes are not new instead they are already existing and being widely used, if the classes contain objects which can't implement Serializable interafce, or some other possible reason which may stop the classes to become Cloneable. This completes our discussion of the popular Creational Design Patterns.


Lastly, you may like to summarize all five creational design patterns. Here is a quick briefing:-


Singleton Design Pattern - used to ensure that there is only one global instance shared by all the consumers. It's normally implemented by having a static field which is assigned to the global instance on its first use.


Factory Design Pattern - used to choose and return an an instance based on some passed parameters. The common base class is used as the return type for all the descendants instances.


Abstract Factory Design Pattern - it provides one level higher abstraction that the Factory Design Pattern and it's used to return one of the many groups based on some passed parameter. These groups are normally implemented using Factory Design Pattern. That means Abstract Factory normally returns Factory :-)


Builder Design Pattern - used for assembing and returing a set of objects based on some passed parameters. The selection is normally made usnig a Factory and the assembly is made by extending common abstract base class.


Prototype Design Pattern - used when instantiation of a class is very complex and/or time-consuming. Instead of direct instantiation and already existing instance is Cloned and the necessary changes and made to the cloned copy.



Share/Save/Bookmark


Monday, September 8, 2008

Creational Patterns - Singleton, Factory, & Abstract Fac


If you're interested in refreshing your understanding of Design Patterns and their Types before moving on to the details of Creational Patterns then you may refer to this article - Design Patterns - Types & Precepts >>


Creational Design Patterns


As the name suggests these design patterns are used to control the instantiation of a class. Why do we need it? Because the program should not be dependent on how an user of the class instantiates it. The supplier of the class should take the responsibility of controlling the instantiation process in case it affects the execution of the program. For Example: if a class is supposed to have only one instance for it to work properly for an application then in such a case the supplier of the class needs to make the necessary arrangements that all the users of that cass get only the one shared instance. This is normally achieved by using the Singleton Design Pattern which we'll discuss next.


Few popular Creational Design Patterns


The Singleton Pattern - this design pattern is used to ensure that only one instance of the class is being used across the entire application. For example: you may like to use this design pattern to implement Cache of an application. How do we implement the singleton Design Pattern? The easiest way is to have a static variable storing the refence of the shared instance and keeping the constructor(s) private so that the users can't call the new operator to create instances. Such an implementation provides a static public method to the consumers to get the shared instance.


class SingletonImpl{
...
private static singletonInstance = null;
...
private SingletonImpl(){
...
}
public synchronized static getSingleton(){
if(singletonInstance == null) singletonInstance = new SingletonImpl();
return singletonInstance;}
...
}


The Factory Pattern - this design pattern is used to return an instance of one of several possible classes depending on what parameters are actually passed by the consumer. How do we implement this design pattern? We normally use inheritance to implement this. Suppose we have a base class named 'Base' and two chilldren of this base class named 'Child1' and 'Child2'. Now the Factory class which is the decision making body based on what the consumer provides decides whether to return an instance of the class 'Child1' or 'Child2'. We can easily set the return type of the method of the Factory (which is exposed to the consumers) as the Base Class type and then the method can easily return instances of either of the two children.


class BaseClass {
...
}
class Child1 extends BaseClass{
...
}
class Child2 extends BaseClass{
...
}
public class FactoryImpl{
...
public BaseClass getChild(String parameter){
...
if(parameter.equals("Child1")) //... sample cond impl

return new Child1();

else return new Child2();
}
...
}


The Abstract Factory Pattern - this design pattern is very similar to the Factory Pattern with the only difference that it takes the abstraction to another level higher. This pattern is basically used to return one of several related classes of objects i.e., one of several Factories (which in turn return the actual instance based on the passed parameter as explained above). One common example of this design pattern is to implement user interfaces. Suppose you're building an UI for three platforms - Windows, Mac, and Linux. Now you can use Abstract Factory pattern to return each of the Factories (Windows, Mac, and Linux) which will themselves return one of the various UI Components based on the passed parameter.


public abstract class UI{
public abstract UIComponent getButton(int, int, int, int);

...
}
public class UIComponent{
private int x1;private int y1;private int x2;private int y2;
public UIComponent(int x1, int y1, int x2, int y2){...}
}
public class Button extends UIComponent{...}

...
public class WindowsUI extends UI{...}
public class UIFactory {
private UI ui;
public UI getUI(String type){
if(type.equals("Win")) ui = new WindowsUI();

...

return ui;

}
}


This is just a sample implementation to help you understand how actually we make use of the Abstract Factory Pattern. The actual UI implmenetation will of course be quite different.


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Design Patterns - Types and suggested Precepts


What are Design Patterns?


Design Patterns are basically a catalog of common interactions between objects. These interactions have been found, tested/tried, and optimized by skilled programmers to help others in solving some of their very common programming problems in an efficient way. Design Patterns simply illustrate how objects can communicate with each other without being much concerned about their individual data models and methods. This clear separation helps building robust and scalable design solutions to various programming problems. If you've already made this separation in your code (which is highly possible in Object Oriented Dev) then you're already using some of the widely used Design Patterns.


There are various formal definitions of Design Patterns and almost all of them convey the same message. Find below one such popular definition given by Gamma, et al., 1993.


“Patterns identify and specify abstractions that are above the level of single classes and instances, or of components.”


What are Communication Patterns?


Design Patterns do discuss design of objects as well, but what makes them even more important is that they describe an elegant and efficient methods of communication between the involved objects and this is the reason why Design Patterns are also referred to as Communication Patterns.


How many Design Patterns are currently available?


There is no fixed answer to this question. The original Design Patterns book included 23 design patterns and these are the most widely used patterns having several known applications using them. But, we currently have hundreds of Design Patterns documented/presented in some form or the other and many of them have already gained a good popularity. There are few which are suitable only for some very specific problems and hence not so popular. These Design Patterns are applicable at many levels ranging from very low level specific problems to general system-wide problems. Understanding of these Design Patterns may become extremely beneficial in designing solutions as they have been found/tested/tried by experts and it's highly unlikely that most of us will come up with a better design on the fly.


Types of Design Patterns


The authors of the original Design Pattern book deivided the 23 patterns into three categories based on what actually the patterns do in a design solution. These categories are:-

  • Creational - the design patterns belonging to these category are used for creating objects. Using such a design pattern provides more flexibility where we require a control over the creation of objects. One very common use case is the usage of a creational design pattern to restrict the total number of instances of a class. Example: The Singleton Pattern, The Abstract Factory Method Pattern, etc. Read more - Creational Design Patterns & their Examples >>
  • Structural - as the name suggests this category groups all those design patterns which help the user to group objects into larger structures to meet the complex requirements in a structured way. A common use case is to use such a design pattern for designing a complex user interface. Example: The Adapter Pattern, The Proxy Pattern, etc. Read more - Structural Design Patterns & their Examples >>
  • Behavioral - the patterns belonging to this category are used to define communication between objects of a proposed solution. In other words such design patterns helps defining the flow of a complex system. Example: The Chain of Responsibility Pattern, The Strategy Pattern, The Iterator Pattern, etc.


What do Design Patterns suggest for Object Oriented programming?


The goal of Design Patterns (as discussed in the first section of the article) is to maintain a clear separation between classes so that they need to know (and hence depend) very little on each other. Object Oriented Programming has two popular mechanisms of enforcing separation which are: Inheritance and Encapsulation. Based on these two separation mechanisms Design Patterns suggest two important precepts which are:-


Programs should be based on Interface and NOT on implementation - If you're using inheritance then you may have unnecessary access to other methods/members of the base class and you may keep carrying all that extra load throughout the inheritance chain and this may subsequently cause many undesirable issues especially when the inheritance chain the underlying system becomes large and complex. You can avoid such a potential issue by having an abstract class at the top of the hierarchy and having the specific implementation in the corresponding sub classes only.


Composition should be preferred over Inheritance - does it seem contrary to the customs of Object Oriented Programming Methodology? Well... it isn't actually. Interitance may cause some undesirable side-effects in certain cases whereas Composition is usually (or probably always) pretty safe to use without worrying about any possible side-effects even when the classes evolve to newer versions which may not be the same in case of Inheritance.


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark