Sunday, August 30, 2009

Patterns - 015: Creational patterns ( Prototype part - 2)

Consider a Web hosting company that offers hosting services on both Windows and UNIX platforms. Suppose that the Web hosting company offers three different types of hosting packages
  • Basic
  • Premium
  • Premium Plus
on both platforms.

Applying the Abstract Factory pattern the application design would have resulted in a factory class hierarchy as shown, Client objects can make use of an appropriate concrete factory class instance to create required HostingPlan objects.



Applying the Prototype pattern, the HostingPlanFactory class hierarchy shown abobe can be replaced with a single concrete class HostingPlanKit.

  • Maintains different prototypical objects that represent different types ofhosting packages in its instance variables.
  • Offers a set of methods that can be used by different client objects to get access to objects representing different hosting plans. As part of its implementation of these methods, it returns copies of the prototypical objects it contains.


For a client object to be able to make use of a HostingPlanKit instance, the HostingPlanKit instance must be configured with appropriate prototypical objects.




         public class HostingPlanKit {

             private HostingPlan basicPlan;
             private HostingPlan premiumPlan;
             private HostingPlan premPlusPlan;

             public HostingPlanKit(HostingPlan basic, HostingPlan premium,
                                   HostingPlan premPlus) {

                 basicPlan = basic;
                 premiumPlan = premium;
                 premPlusPlan = premPlus;
             }

             public HostingPlan getBasicPlan() {
                 return (HostingPlan) basicPlan.clone();
             }

             public HostingPlan getPremiumPlan() {
                 return (HostingPlan) premiumPlan.clone();
             }

             public HostingPlan getPremPlusPlan() {
                 return (HostingPlan) premPlusPlan.clone();
             }
         }         
     

Let us design a separate class HostingPlanManager with the responsibility of configuring a HostingPlanKit object with appropriate prototypical objects and return it to client objects.







           public class HostingPlanManager {

               public static HostingPlanKit getHostingPlanKit(
                       String platform) {

                   HostingPlan basicPlan = null;
                   HostingPlan premiumPlan = null;
                   HostingPlan premPlusPlan = null;

                   if (platform.equalsIgnoreCase("Win")) {
                       basicPlan = new WinBasic();
                       premiumPlan = new WinPremium();
                       premPlusPlan = new WinPremPlus();
                   }
                   if (platform.equalsIgnoreCase("Unix")) {
                       basicPlan = new UnixBasic();
                       premiumPlan = new UnixPremium();
                       premPlusPlan = new UnixPremPlus();
                   }
                   return new HostingPlanKit(basicPlan, premiumPlan,
                           premPlusPlan);
               }
           }
       

The HostingPlanManager offers a static method getHostingPlanKit that can be used by client objects to get access to a HostingPlanKit object configured with prototypical HostingPlan objects that represent hosting plans on the specified platform. As an alternative design strategy, the static method getHostingPlanKit can be designed as part of the HostingPlanKit class itself.

Once the HostingPlanKit object is received, a client can make use of getBasicPlan/getPremiumPlan/getPremPlusPlan methods to get access to HostingPlan objects.


Example


A computer user in a typical organization is associated with a user account. A user account can be part of one or more groups. Permissions on different resources (such as servers, printers, etc.) are defined at the group level. A user gets all the permissions defined for all groups that his or her account is part of. Let us build an application to facilitate the creation of user accounts. For simplicity, let us consider only two groups — Supervisor and AccountRep — representing users who are supervisors and account representatives,respectively.


For simplicity, let us define the set of permissions for each of the Supervisor and the AccountRep groups in the form of two text files — supervisor.txt and accountrep.txt, respectively. With this arrangement, one of the simplest ways to

create a user account is to:
  • Instantiate the UserAccount class
  • Read permissions from an appropriate data file
  • Set these permissions in the UserAccount object
Though this approach looks straightforward, it is not efficient as it involves expensive file I/O (input/output) each time an account is created. This process can be designed more efficiently using the Prototype pattern. Applying the Prototype pattern, let us make the following changes to the design.







Patterns - 014: Creational patterns ( Prototype part - 1)


While addressing the same problem as the Factory Method and Abstract Factory patterns, the Prototype pattern offers a different, more flexible way of achieveing the same result.

Other uses of the Prototype pattern include:
  • When a client needs to create a set of objects that are alike or differ from each other only in terms of their state and it is expensive to create such objects in terms of the time and the processing involved.
  • As an alternative to building numerous factories that mirror the classes to be instantiated (as in the Factory Method).
In such cases, the Prototype pattern suggests to:
  • Create one object upfront and designate it as a prototype object.
  • Create other objects by simply making a copy of the prototype object and making required modifications.

when using the Prototype pattern, a system should be independent of the creation, composition and representation details of the objects it uses.

One of the requirements of the prototype object is that it should provide a way for clients to create a copy of it. By default, all Java objects inherit the builtin clone() method from the topmost java.lang.Object class. The built-in clone() method creates a clone of the original object as a shallow copy.

SHALLOW COPY VERSUS DEEP COPY


When an object is cloned as a shallow copy:

  • The original top-level object and all of its primitive members are duplicated.
  • Any lower-level objects that the top-level object contains are not duplicated. Only references to these objects are copied. This results in both the orginal and the cloned object referring to the same copy of the lower-level object.




class Person implements Cloneable {
//Lower-level object
private Car car;

private String name;

public Car getCar() {
   return car;
}

public String getName() {
   return name;
}

public void setName(String s) {
   name = s;
}

public Person(String s, String t) {
   name = s;
   car = new Car(t);
}

public Object clone() {
   //shallow copy
   try {
       return super.clone();
   } catch (CloneNotSupportedException e) {
       return null;
   }
}
}




In contrast, when an object is cloned as a deep copy:


  • The original top-level object and all of its primitive members are duplicated.
  • Any lower-level objects that the top-level object contains are also duplicated. In this case, both the orginal and the cloned object refer to two different lower-level objects.




class Person implements Cloneable {
 //Lower-level object
 private Car car;

 private String name;

 public Car getCar() {
     return car;
 }

 public String getName() {
     return name;
 }

 public void setName(String s) {
     name = s;
 }

 public Person(String s, String t) {
     name = s;
     car = new Car(t);
 }

 public Object clone() {
     //Deep copy
     Person p = new Person(name, car.getName());
     return p;
 }
}





Patterns - 013: Creational patterns ( abstract factory )


In simple terms, an abstract factory is a class that provides an interface to produce a family of objects. In the Java programming language, it can be implemented either as an interface or as an abstract class.

In the context of an abstract factory there exist:

  • Suites or families of related, dependent classes.
  • A group of concrete factory classes that implements the interface provided by the abstract factory class. Each of these factories controls or provides access to a particular suite of related, dependent objects and implements the abstract factory interface in a manner that is specific to the family of classes it controls.

The Abstract Factory pattern is useful when a client object wants to create an instance of one of a suite of related, dependent classes without having to know which specific concrete class is to be instantiated. In the absence of an abstract factory, the required implementation to select an appropriate class (in other words, the class selection criterion) needs to be present everywhere such an instance is created. An abstract factory helps avoid this duplication by providing the necessary interface for creating such instances.

This is useful for plugging in a different group of objects to alter the behavior of the system.


This situation often arises when designing a framework or a library, which needs to be kept extensible. One example is the JDBC (Java Database Connectivity) driver system.


ProtoType







Example

Select Cars and SUV under the categories of Luxury and NonLuxury.





Saturday, August 29, 2009

Patterns - 012: Creational patterns ( singleton )



Sometimes, there may be a need to have one and only one instance of a given class during the lifetime of an application.


A class that maintains its single instance nature by itself is referred to as a Singleton class.

Example

Use singolton FileLogger class to log messages to the file, because there is only one physical log file. In an application, when different client objects try to log messages to the file, there could potentially be multiple instances of the FileLogger class in use by each of the client objects.
This could lead to different issues due to the concurrent access to the same file by different objects.




  • Make the Constructor Private : Making the constructor private prevents client objects from creating FileLogger objects by invoking its constructor. At the same time, other methods inside FileLogger will have access to the private constructor.
  • Static Public Interface to Access an Instance : Provide a public interface, in the form of a static method FileLogger , for clients to be able to get access to an instance of the FileLogger class.





Patterns - 011: Creational patterns ( factory method )


At times, an application object may only know that it needs to access a class from within the class hierarchy, but does not know exactly which class from among the set of subclasses of the parent class is to be selected. The choice of an appropriate class may depend on factors such as:
  • The state of the running application
  • Application configuration settings
  • Expansion of requirements or enhancements

In such cases, the Factory Method pattern recommends encapsulating the functionality required, to select and instantiate an appropriate class, inside a designated method referred to as a factory method. Thus, a factory method can be defined as a method in a class that:

  • Selects an appropriate class from a class hierarchy based on the application context and other influencing factors
  • Instantiates the selected class and returns it as an instance of the parent class type

One of the simplest ways of designing a factory method is to create an abstract class or an interface that just declares the factory method. Different subclasses (or implementer classes in the case of an interface) can be designed to implement the factory method. Another strategy is to create a concrete creator class with default implementation for the factory method in it. Different subclasses of this concrete class can override the factory method to implement specialized class selection criteria.

Prototype



Example


Consider an application object that intends to use the services provided by the Logger implementers. Suppose that the overall application message logging configuration can be specified using the logger.properties property file.



Depending on the value of the FileLogging property, an appropriate Logger implementer needs to be used to log messages. For example, if the FileLogging property is set to ON, messages are to be logged to a file and hence a FileLogger object can be used to log messages. Similarly, if the FileLogging property is set to OFF, messages are to be displayed on the console and hence a ConsoleLogger object can be used.

To log messages, an application object needs to:
  • Identify an appropriate Logger implementer by reading the FileLogging property value from the logger.properties file
  • Instantiate the Logger implementer and invoke the log method by passing the message text to be logged as an argument






Patterns - 010: Creational patterns


Creational patterns
  • Deal with one of the most commonly performed tasks in an OO application,the creation of objects.
  • Support a uniform, simple, and controlled mechanism to create objects
  • Allow the encapsulation of the details about what classes are instantiated and how these instances are created.
  • Encourage the use of interfaces, which reduces coupling.



Pattern Name Description
Factory Method When a client object does not know which class to
instantiate, it can make use of the factory method to create an instance of an appropriate class from a class hierarchy
or a family of related classes. The factory method may be
designed as part of the client itself or in a separate class.
The class that contains the factory method or any of its
subclasses decides on which class to select and how to
instantiate it.
Singleton Provides a controlled object creation mechanism to ensure
that only one instance of a given class exists.
Abstract Factory Allows the creation of an instance of a class from a suite of
related classes without having a client object to specify the
actual concrete class to be instantiated.
Prototype Provides a simpler way of creating an object by cloning it
from an existing (prototype) object.
Builder
Allows the creation of a complex object by providing the

information on only its type and content, keeping the
details of the object creation transparent to the client. This
allows the same construction process to produce different
representations of the object.

Patterns - 009: Basic java patterns ( Monitor )


Patterns - 008: Basic java patterns ( Immutable Object )


Patterns - 007: Basic java patterns ( Constant Data Manager )


Patterns - 006: Basic java patterns ( Accessor Methods )


Patterns - 005: Basic java patterns ( Private Methods )


Patterns - 004: Basic java patterns ( Abstract )


The Abstract Parent Class pattern is useful for designing a framework for the consistent implementation of functionality common to a set of related classes. An abstract method is a method that is declared, but contains no implementation.

An abstract class is a class with one or more abstract methods. Abstract methods, with more than one possible implementation, represent variable parts of the behavior of an abstract class. An abstract class may contain implementations for other methods, which represent the invariable parts of the class functionality.
Different subclasses may be designed when the functionality outlined by abstract methods in an abstract class needs to be implemented differently. An abstract class, as is, may not be directly instantiated. When a class is designed as a subclass of an abstract class, it must implement all of the abstract methods declared in the parent abstract class. Otherwise the subclass itself becomes an abstract class. Only nonabstract subclasses of an abstract class can be instantiated. The requirement that every concrete subclass of an abstract class must implement all of its abstract methods ensures that the variable part of the functionality will be implemented in a consistent manner in terms of the method signatures. The set of methods implemented by the abstract parent class is automatically inherited by all subclasses. This eliminates the need for redundant implementations of these methods by each subclass.


In the Java programming language there is no support for multiple inheritance. That means a class can inherit only from one single class. Hence inheritance should be used only when it is absolutely necessary. Whenever possible, methods denoting the common behavior should be declared in the form of a Java interface to be implemented by different implementer classes. But interfaces suffer from the limitation that they cannot provide method implementations. This means that every implementer of an interface must explicitly implement all methods declared in an interface, even when some of these methods represent the invariable part of the functionality and have exactly the same implementation in all of the implementer classes. This leads to redundant code. The following example demonstrates how the Abstract Parent Class pattern can be used in such cases without requiring redundant method implementations.

Employee calss with Interface design.



Employee calss with Abstract parent design.





Friday, August 28, 2009

Patterns - 003: Basic java patterns ( Interface )


Applying the Interface pattern, the common services offered by different service provider classes can be abstracted out and declared as a separate interface. Each of the service provider classes can be designed as implementers of this common interface.
With this arrangement, the client can safely assume the service provider object to be of the interface type.objects of different service provider classes can be treated as objects of the interface type. This enables the client to use different types of service provider objects in a seamless manner without requiring any changes. The client does not need to be altered even when a new service provider is introduced.

Prototype



Example



Let us build an application to calculate and display the salaries of dif ferent
employees of an organization with the categorization of designations as listed in

DesignationsCategory
Programmer, Designer and ConsultantCategory-A
Sales Rep, Sales Manager, Account RepCategory-B
C-Level ExecutivesCategory-n



Poor design

Let us assume that the application needs to consider only those employees whose designations are part of Category-A. And we design the application only for the Category-A. But when later found the Category-B. Then we have to Alter the emplyee class and make it compatible with the Category-B also. So this a result of bad poor design.








Correct Design









Patterns - 002: Basic java patterns


BASIC PATTERNS

In general, the functionality of an object-oriented system is encapsulated in the form of a set of objects. These objects provide different services either on their own or by interacting with other objects. In other words, a given object may rely upon the services offered by a different object to provide the service it is designed for. An object that requests a service from another object is referred as a client object. Some other objects in the system may seek the services offered by the client object.



Pattern NameDescription
InterfaceCan be used to design a set of service provider classes
that offer the same service so that a client object can
use different classes of service provider objects in a
seamless manner without having to alter the client
implementation.
Abstract Parent ClassUseful for designing a framework for the consistent
implementation of the functionality common to a set of
related classes.
Private MethodsProvide a way of designing a class behavior so that
external objects are not permitted to access the
behavior that is meant only for the internal use.
Accessor MethodsProvide a way of accessing an object’s state using specific
methods. This approach discourages different client
objects from directly accessing the attributes of an
object, resulting in a more maintainable class structure.
Constant Data ManagerUseful for designing an easy to maintain, centralized
repository for the constant data in an application.
Immutable ObjectUsed to ensure that the state of an object cannot be
changed. May be used to ensure that the concurrent
access to a data object by several client objects does not
result in race conditions.
MonitorA way of designing an application object so that it does
not produce unpredictable results when more than one
thread tries to access the object at the same time in a
multithreaded environment.

UML: Notations ( Sequence Diagram )


Object
An object is represented with the name of the class in a rectangle preceded by a colon.

Message
A message is a communication between objects. The solid horizontal line indicating a message can be labeled with the name of the message/operation along with its argument values.

Self Call
This is a message call from an object onto itself.



Example







UML: Association


Class Association
Class association specifies the structural relationship between classes. The concept of multiplicity discussed below is very closely tied to class associations.


Multiplicity
Multiplicity is used to indicate the number of instances of one class linked to one instance of the other class.

  • [ 1 ] ------- No More than One
  • [ 0..1 ] ---- Zero or One
  • [ * ] ------- Many
  • [0..* ] ----- Zero or Many
  • [1..* ] ----- One or Many

Navigability
When Class A contains the information required to reach Class B, then the navigability is from Class A to Class B. In other words, Class A knows about Class B, but not vice versa.
An instance of the LogAbstraction class internally maintains a LoggerBridge object and hence will be able to reach it directly. Hence a LoggerBridge object is navigable from a LogAbstraction instance.


It is also possible for the navigability to be bidirectional. In that case, the solid line of association between the two classes either contains arrowheads on both the ends or none.


whole–part relationship

Composition
Class A contains Class B.This statement denotes a strong ownership between Class A, the whole, and Class B, its part. In other words, the part class cannot meaningfully exist on its own without the whole class.

  • A line item is part of an order.
  • A line item cannot exist without an order.

Aggregation
This is a lighter form of composition. The whole class plays a more important role than the part class, but unlike the case of composition, the part class can meaningfully exist on its own without the whole class.

  • A Player is part of a Team.
  • A Player can be part of more than one Team and hence, when a Team is dissolved, the Player still remains.