Showing posts with label Pattern. Show all posts
Showing posts with label Pattern. Show all posts

Sunday, October 24, 2010

Design Pattern-2

As it was not possible to cover all the pattern in the previous post. In this post I am going to summarize the other design patterns.
Structural Patterns
Adapter: This pattern is called Wrapper pattern as well. Using this pattern, one class is made compatible with another class. For example, interface X defines 2 methods get and put. Class LegacyClass has methods implementing the required functionality but as LegacyClass can not implement newly defined interface X. So there is a need to wrap LegacyClass with Interface. Adapter pattern will provide the solution to break the ice.
Bridge: This pattern is to provide encapsulation, inheritance and abstraction to the code. In this pattern one interface is given whose implementation can be provided at lower class hierarchy keeping it hidden from the client.
Composite: Composition of no of objects to form an object. This pattern suggests to use numerous objects to create one object.
Decorator: The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.
Facade: Provide one unified interface to a set of interfaces. This unified interface works at higher level and it makes it easy to use all the interfaces at once.
Flyweight: A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
Private Class Data: This pattern primarily deals with encapsulation to hide the data.
Proxy: A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.

Behavioral patterns
Chain of responsibility pattern: This pattern is a source of command object and series of processing objects. Each processing object contains a set of logic that describes the types of command objects that it can handle, and how to pass off those that it cannot handle to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
Command pattern: In this pattern object stores the information to invoke the method at later point of time. The information stored is method’s name. parameters and object to which method belongs to. There are 3 components of the pattern:
  • Client: Instantiate a command object and provide the information required to call the method at later point of time.
  • Invoker: Class which decides when to call the method.
  • Receiver: Object having method.
Interpreter pattern: Rules to identify the sentence in language. This pattern is generally used when someone needs to implement own parser.
Iterator pattern: There are aggregated data and there is need to access the data sequentially. So with exposing the internal DS, the same problem is solved by iterator patterns. Java collection API uses iterator pattern.
Mediator pattern: It is very similar facade patterns, where unified interface is exposed by extending numerous interfaces in the subsystem. This pattern is used in these circumstances.
  • Partition a system into pieces or small objects.
  • Centralize control to manipulate participating objects(a.k.a colleagues)
  • Clarify the complex relationship by providing a board committee.
  • Limit subclasses.
  • Improve objects re-usabilities.
  • Simplify object protocols.
  • The relationship between the control class and other participating classes is multidirectional.
Memento pattern: This pattern provide the ability to roll back. Here you will keep 2 states of an object one that is original i.e. anything before changes whereas other object will have latest copy with updates. This pattern is utilized in database updates.
Null Object pattern: Pattern just portrait the behavior of nothing.
Observer pattern: In this pattern a object keeps the list of its dependent, called observer. Whenever changes happened in the object its observer are notified by calling some methods. In general this pattern is used in event handling.
Weak reference pattern: A WeakReferencePattern is a structural pattern used when decoupling of an observer (a view) from an observable (a container) is necessary. A WeakReferencePattern encapsulates a reference to an object. Acquiring the reference is done through a message to the WeakReference (or WeakPointer) object. If the referenced object still exists, a real reference to it is returned. This reference is of course a temporary one.
State pattern: As the state of the object changes behavior is changed. Behavior is changes with if and else statements.

Strategy pattern: The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them. It is useful in the following situations
  • Encapsulate various algorithms to do more or less the same thing.
  • Need one of several algorithms dynamically.
  • The algorithms are exchangeable and vary independently
  • Configure a class with one of many related classes (behaviors).
  • Avoid exposing complex and algorithm-specific structures.
  • Data is transparent to the clients.
  • Reduce multiple conditional statements.
  • Provide an alternative to subclassing.
Specification pattern: In this pattern business logic can be recombined by chaining the business logic together using boolean logic.
Template method pattern: Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended. Provide an abstract definition for a method or a class and redefine its behavior later or on the fly without changing its structure.
Visitor pattern: Define a new operation to deal with the classes of the elements without changing their structures. These are used in the following circumstance:
  • Add operations on a bunch of classes which have different interfaces.
  • Traverse the object structure to gather related operations
  • Easy to add new operations.
  • Crossing class hierarchies may break encapsulation.
Apart from above described patterns there are lot more patterns few of them are Single-serving visitor pattern, Hierarchical visitor pattern and Scheduled-task pattern. There are lot other than mentioned here so it is quite impossible to cover all of them. Hope this information will help all of us.


Source:

Sunday, October 10, 2010

ArrayList V/S Vector

ArrayList and Vector are widely known classes in Java world. Most of the interviewer start their discussion to explore differences between ArrayList and Vector (Sometime interviewer also forget no of differences also has limitations :(), and Just after answering this question candidates are pulled into the world of multithreading. Oh I am not going to talk about multithreading here, I will stick to title here.
Legacy Java code has used vector enormous time. For all general indexing purposes vector classes were used. But with the evolution of Java 5, vector classes lost its ground to ArrayList and Collections framework’s utility class SynchromizedList. Now it is really mandatory to know the similarity and differences between these Vector and ArrayList.

Inheritance and Hierarchy
Both the classes implements List, RandomAccess, Cloneable and Serializable interfaces. Along with that both of them extends AbstractList class.

Structure
In general both the classes have same work. Completion of the work is also quite common between both of them but still they have major differences also.


Constructor
ArrayList has 3 constructors whereas Vector has 4 constructors as shown below:

ArrayList() Vector() Default constructor instantiate an Array, containing 10 elements.
ArrayList(int capacity) Vector(int capacity)
Constructor instantiate an Array, containing Capacity elements.
Vector(int capacity, int loadfactor)

Constructor instantiate an Array containing Capacity elements. When someone adds more element than capacity, it re-instantiate the array. The new Array will have (Loadfactor + 1)*Capacity number of elements.

ArrayList(Collection) Vector(Collection) All the elements of the collection are copied to the array.


ArrayList does have user defined load factor which will impact performance when user is not aware of no of incoming elements. Reassignment of the elements will be more and more time consuming. For ArrayList load factor is 0.5 in case of Vector it is defaulted to 1.

Note: It is good practice to use LinkedList if number of elements are more and you are not doing any search operations on the basis of index.

Multithreading
Major difference is associated with Multithreading. All the method of the vector class are synchronized. When multiple threads are trying to access specific instance of vector class, then the calls will not cause any issue. Vector is a thread safe class but not ArrayList. Hence Vector class is slow performing class whereas array list access is faster.
Note: To use iterator on vector, you might need to synchronize the code.

Patterns
Adding and deletion in both the structures take O(1) time. It may take O(N) time just when array capacity has shoot the maximum size assigned. Indexing based search on both the APIs are similar as both of them use array internally.

Serialization
Array object in the ArrayList is a transient object, so while serializing the ArrayList it is required to serialize the object individually. For this reason ArrayList implements readObject and writeObject methods. In case of vector Array object is not transient. Vector implements only writeObject method.

Iterator
ArrayList has not provided any iterator whereas in vector is quipped with its own iterator/enumeration.

These were the differences I could make out from code and different geek sites. If you are aware of any other difference let me know.