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.
Sunday, September 28, 2008
Structural Patterns - Adapter, Decorator, Composite, etc.
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.
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.
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.
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.
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.
Design Patterns - Types and suggested Precepts
What are Design Patterns? 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.
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:-
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:-
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.