Design Patterns

DESIGN PATTERNSThere are three design patterns described. They are as follows:1)Structural2)Creational3)BehavioralStructural PatternsStructural Patterns describe how objects and classes can be combined to form larger structures.There are seven structural patterns described. They are as follows:1.Adapter2.Bridge3.Composite4.Decorator5.Facade6.Flyweight7.ProxyDecorator pattern attaches additional responsibilities to an object dynamically. Provide a flexible alternative to subclassing for extending functionality.It is used in various Java IO classes. java.io.BufferedReader; java.io.FileReader;java.io.Reader;It’s a structural design pattern.Decorator pattern allows to add new functionality an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class. This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.AdvantageDecorator Pattern is flexible than inheritance because inheritance add responsibilities at compile time and it will add at run-time.DisadvantageCode maintenance can be a problem as it provides a lot of similar kind of small objects (each decorator).ImplementationThe decorator pattern helps to add behavior or responsibilities to an object. This is also called “Wrapper”. Suppose we have some 6 objects and 2 of them need a special behavior, we can do this with the help of a decorator.Java Design Patterns suggest that Decorators should be abstract classes and the concrete implementation should be derived from them. The decorator pattern can be use wherever there is a need to add some functionality to the object or group of objects. Let’s take an example of a Christmas tree. There is a need to decorate a Christmas tree. Now we have many branches which need to be decorated in different ways.
Let’s have a look at the basic Decorator class.ImplementationThe decorator pattern helps to add behavior or responsibilities to an object. This is also called “Wrapper”. Suppose we have some 6 objects and 2 of them need a special behavior, we can do this with the help of a decorator.**Decorator.java**
public abstract class Decorator {
public abstract void place(Branch branch);
}// End of class
This class has just one method place(). This method places different types of items on the branches of the tree.The class ChristmasTree is very simple and has just one method which returns a branch.
**ChristmasTree.java**
public class ChristmasTree {
private Branch branch;
public Branch getBranch() {
return branch;
}
}// End of classNow we can decorate the branches in three different ways, one is by putting coloured balls on them, by putting coloured ruffles on them and also by putting stars on them.Let’s have a look at the implementation of these three different types of decorators.**BallDecorator.java** /*** Decorates the branch of the tree with* coloured balls.*/
public class BallDecorator extends Decorator {
// Default Constructor
public BallDecorator(ChristmasTree tree) {
Branch branch = tree.getBranch();
place(branch);
} /** The method places each decorative item* on the tree.*/
public void place(Branch branch) {
branch.put(“ball”);
}
}// End of classSimilarly, we can make StarDecorator and RufflesDecorator.Now, we will see how to use the decorator. Its simple, we just are needed to pass the instance of ChristmasTree class to a decorator.StarDecorator decorator = new StarDecorator(new ChristmasTree());This way the decorator will be instantiated and a branch of the Christmas tree will be decorated.Structural Patterns – Adapter PatternThe Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter. This is something likewe convert interface of one class into interface expected by the client.We do that using an Adapter.Let’s try and understand this with the help of an example.Again, I will like to take a general example. We all have electric sockets in our houses of different sizes and shapes. I will take an example of a socket of 15 Ampere. This is a bigger socket and the other one which is smaller is of 5 Ampere. A 15 Amp plug cannot fit into a 5 Amp socket. Here, we will use an Adapter. The adapter can be called a connector here. The connector connects both of these and gives output to the client plug which is of 5Amp.The Adapter is something like this. It will be having the plug of suitable for 15 Amp and a socket suitable for a 5 Amp plug. So, that the 5 Amp plug which here is the client can fit in and also the server which here is the 15 Amp socket can give the output.Let’s try and convert the same example into a software program. How do we do this? Let’s try and understand the problem once more. We have a 5 Amp plug and want a 5 Amp socket so that it can work. We DO NOT have a 5 Amp socket, what we have is a 15 Amp socket in which the 5 Amp plug cannot fit. The problem is how to cater to the client without changing the plug or socket.The Adapter Pattern can be implemented in two ways, by Inheritance and by Composition.
Here is the example of Adapter by Inheritance:Let’s say there is a socket interface.**Socket.java** /*** The socket class has a specs for 15 AMP.*/
public interface Socket {
/*** This method is used to match the input to be* given to the Plug
* @return Output of the Plug (Client)*/
public String getOutput();
}// End of interface
And there is a class Plug which wants the input of 5 AMP. This is the client.
**Plug.java** /*** The input for the plug is 5 AMP. which is a* mismatch for a 15 AMP socket.
** The Plug is the client. We need to cater to* the requirements of the Plug.*/
public class Plug {
private String specification = “5 AMP”;
public String getInput() {
return specification;
}
}// End of classFinally, there will be an adapter class. This will inherit the socket and give output for Plug.**ConnectorAdapter.java** /*** ConnectorAdapter has is the connector between* the socket and plug so as to make the interface* of one system to suit the client.*/
public class ConnectorAdapter implements Socket {
/*** Method coming from the interface* Socket which we have to make to
* fit the client plug * @return Desired output of 5 AMP*/
public String getOutput() {
Plug plug = new Plug();
String output = plug.getInput();
return output;
}
}// End of classThis class implements the getOutput() method of Socket and sets it to fit the client output.Similarly, let’s consider the Association and Composition of objects by which Adapter can be implemented.The class Socket gives the 15 AMP output.**Socket.java**/*** Class socket giving the 15 AMP output.*/
public class Socket {
/**
* Output of 15AMP returned.
*
* @return Value of output from socket
*/
public String getOutput() {
return “15 AMP”;
}
}// End of classThere is an interface Plug.java which has a method getInput(). This is the client and we need to adapt the output for this input which is 5 AMP.
Plug.java/*** The input for the plug is 5 AMP. which is a
* mismatch for a 15 AMP socket.** The Plug is the client. We need to cater to* the requirements of the Plug.*/
public interface Plug {
public String getInput();
}// End of class
Plug5AMP is the implementation of Plug which requires 5 AMP of input.
Plug5AMP.java
public class Plug5AMP implements Plug {
/*** Get the input of client i.e. Plug* @return 5 AMP*/
public String getInput() {
return “5 AMP”;
}
}// End of classThe Adapter here takes output from the Socket. If the output is what is needed, it gives it to the Plug else, it overrides the value and returns the adapter output.ConnectorAdapter.java
/*** Using composition*/
public class ConnectorAdapter {
Plug5AMP plug5;
public ConnectorAdapter(Plug5AMP plug) {
this.plug5 = plug;
}
public static void main(String[] args) {
// Taking output from the Socket
Socket socket = new Socket();
String outputFromSocket = socket.getOutput();
// Giving away input to the Plug
ConnectorAdapter adapter = new ConnectorAdapter(new Plug5AMP());
String inputToPlug = adapter.getAdapterOutput(outputFromSocket);
System.out.println(“New output by adapter is: “+inputToPlug);
}
public String getAdapterOutput(String outputFromScoket) {
/** if output is same, return*/
if (outputFromScoket.equals(plug5.getInput())) {
return outputFromScoket;
}
/** Else, override the value by adapterOutput*/
else {
String adapterOutput = plug5.getInput();
return adapterOutput;
}
}// End of classConclusionThis is how the Adapter pattern works.
When one interface cannot be changed and has to be suited to the again cannot-be-changed client, an adapter is used so that both the interfaces can work together.Structural Patterns – Bridge PatternThe Bridge Pattern is used to separate out the interface from its implementation. Doing this gives the flexibility so that both can vary independently.The best example for this is like the electric equipments you have at home and their switches. For e.g., the switch of the fan. The switch is the interface and the actual implementation is the Running of the fan once its switched-on. Still, both the switch and the fan are independent of each other. Another switch can be plugged in for the fan and this switch can be connected to light bulb.Let’s see how we can convert this into a software program. Switch is the interface having two functions, switchOn() and switchOff().Here is the sample code for Switch.
Switch.java /*** Just two methods. on and off.*/
public interface Switch {
// Two positions of switch.
public void switchOn();
public void switchOff();
}// End of interface
This switch can be implemented by various devices in house, as Fan, Light Bulb etc. Here is the sample code for that.
Fan.java /** Implement the switch for Fan*/
public class Fan implements Switch {
// Two positions of switch.
public void switchOn() {
System.out.println(“FAN Switched ON”);
}

public void switchOff() {
System.out.println(“FAN Switched OFF”);
}
}// End of class
And implementation as Bulb.
Bulb.java /*** Implement the switch for Fan*/
public class Bulb implements Switch {
// Two positions of switch.
public void switchOn() {
System.out.println(“BULB Switched ON”);
}
public void switchOff() {
System.out.println(“BULB Switched OFF”);
}
}// End of classHere, we can see, that the interface Switch can be implemented in different ways. Here, we can easily use Switch as an interface as it has only two functions, on and off. But, there may arise a case where some other function be added to it, like change() (change the switch). In this case, the interface will change and so, the implementations will also changed, for such cases, you should use the Switch as abstract class. This decision should be made earlier to implementation whether the interface should be interface or abstract class.Structural Patterns – Composite PatternIn developing applications, we come across components which are individual objects and also can be collection of objects. Composite pattern can represent both the conditions. In this pattern, you can develop tree structures for representing part-whole hierarchies.The most common example in this pattern is of a company’s employee hierarchy. We here will also take the same example.The employees of a company are at various positions. Now, say in a hierarchy, the manager has subordinates; also the Project Leader has subordinates, i.e. employees reporting to him/her. The developer has no subordinates.So, let’s have a look at the class Employee: This is a simple class with getters and setters for attributes as name, salary and subordinates.**Employee.java**
import java.util.Vector;
public class Employee {
private String name;
private double salary;
private Vector subordinates;
public Vector getSubordinates() {
return subordinates;
}
public void setSubordinates(Vector subordinates) {
this.subordinates = subordinates;
}
// constructor
public Employee(String name, double sal) {
setName(name);
setSalary(sal);
subordinates = new Vector();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void add(Employee e) {
subordinates.addElement(e);
}
public void remove(Employee e) {
subordinates.remove(e);
}
}// End of interface
Next we, fill up the tree. You can make a class to access the class Employee and try filling up the tree like this:
/** This will add employess to the tree. The boss, is PM* and has subordinates.*/
private void addEmployeesToTree() {
CFO = new Employee(“CFO”, 30000);
Employee headFinance1 = new Employee(“Head Finance. North Zone”, 20000);
Employee headFinance2 = new Employee(“Head Finance. West Zone”, 22000);
Employee accountant1 = new Employee(“Accountant1”, 10000);
Employee accountant2 = new Employee(“Accountant2”, 9000);
Employee accountant3 = new Employee(“Accountant3”, 11000);
Employee accountant4 = new Employee(“Accountant4”, 12000);
CFO.add(headFinance1);
CFO.add(headFinance2);
headFinance1.add(accountant1);
headFinance1.add(accountant4);
headFinance2.add(accountant2);
headFinance2.add(accountant3);
}// End of classOnce we have filled the tree up, now we can get the tree for any employee and find out whether that employee has subordinates with the following condition.
Vector subOrdinates = emp.getSubordinates();
if (subOrdinates.size() != 0)
getTree(subOrdinates);
else
System.out.println(“No Subordinates for the Employee: “+emp.getName());Thus the Composite pattern allows you to create a tree like structure for simple and complex objects so they appear the same to the client.Structural Patterns – Facade PatternFacade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face.This is how facade pattern is used.It hides the complexities of the system and provides an interface to the client from where the client can access the system.In Java, the interface JDBC can be called a facade. We as users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. The implementation is left to the vendor of driver.Let’s try and understand the facade pattern better using a simple example. Let’s consider a store. This store has a store keeper. In the storage, there are a lot of things stored e.g. packing material, raw material and finished goods.You, as client want access to different goods. You do not know where the different materials are stored. You just have access to store keeper who knows his store well. Whatever you want, you tell the store keeper and he takes it out of store and hands it over to you on showing him the credentials. Here, the store keeper acts as the facade, as he hides the complexities of the system Store. Let us see how the Store example works.**Store.java**
public interface Store {
public Goods getGoods();
}// End of interface
The store can very well be an interface. This only returns Goods. The goods are of three types as discussed earlier in this document. RawMaterialGoods, FinishedGoods and PackagingMaterialsGoods. All these classes can implement the Goods interface.Similarly, the stores are of three types and can implement the Store interface. Let’s have a look at the code for one of the stores.
**FinishedGoodsStore.java**
public class FinishedGoodsStore implements Store {
public Goods getGoods() {
FinishedGoods finishedGoods = new FinishedGoods();
return finishedGoods;
}
}// End of class
Now let’s consider the facade StoreKeeper.
**StoreKeeper.java**
public class StoreKeeper {
/*** The raw materials are asked for and* are returned
** @return raw materials*/
public RawMaterialGoods getRawMaterialGoods() {
RawMaterialStore store = new RawMaterialStore();
RawMaterialGoods rawMaterialGoods = (RawMaterialGoods)store.getGoods();
return rawMaterialGoods;
}
/*** The packaging materials are asked for and* are returned** @return packaging materials*/
public PackingMaterialGoods getPackingMaterialGoods() {
PackingMaterialStore store = new PackingMaterialStore();
PackingMaterialGoods packingMaterialGoods = (PackingMaterialGoods)store.getGoods();
return packingMaterialGoods;
}
/*** The finished goods are asked for and* are returned
** @return finished goods*/
public FinishedGoods getFinishedGoods() {
FinishedGoodsStore store = new FinishedGoodsStore();
FinishedGoods finishedGoods = (FinishedGoods)store.getGoods();
return finishedGoods;
}
}// End of class
This is clear that the complex implementation will be done by StoreKeeper himself. The client will just access the StoreKeeper and ask for either finished goods, packaging material or raw material.How will the client program access this façade? Here is a simple code.
**Client.java**
public class Client {
/*** to get raw materials*/
public static void main(String[] args) {
StoreKeeper keeper = new StoreKeeper();
RawMaterialGoods rawMaterialGoods = keeper.getRawMaterialGoods();
}
}// End of class
In this way the implementation is left to the façade. The client is given just one interface and can access only that. This hides all the complexities.There is another way of implementing this. We can have just one method in our StoreKeeper class getGoods(String goodsType).
Another version of StoreKeeper method is here.
**StoreKeeper.java**
public class StoreKeeper {
/*** The common method** @return Goods*/
public Goods getGoods(String goodsType) {
if (goodsType.equals(“Packaging”)) {
PackingMaterialStore store = new PackingMaterialStore();
PackingMaterialGoods packingMaterialGoods = (PackingMaterialGoods)store.getGoods();
return packingMaterialGoods;
}
else if (goodsType.equals(“Finished”)) {
FinishedGoodsStore store = new FinishedGoodsStore();
FinishedGoods finishedGoods = (FinishedGoods)store.getGoods();
return finishedGoods;
}
else {
RawMaterialStore store = new RawMaterialStore();
RawMaterialGoods rawMaterialGoods = (RawMaterialGoods)store.getGoods();
return rawMaterialGoods;
}
}// End of classThe client program can now create an object of StoreKeeper class and call method getGoods() passing as parameter the type of goods required. This can be done as follows.
new StoreKeeper().getGoods(“RawMaterials”);In this case, the type-casting ill be needed on client side to narrow down Goods to RawMaterialsGoods.All in all, the Façade pattern hides the complexities of system from the client and provides a simpler interface. Looking from other side, the facade also provides the implementation to be changed without affecting the client code.Structural Patterns – Proxy PatternThe proxy pattern is used when you need to represent a complex with a simpler one. If creation of object is expensive, its creation can be postponed till the very need arises and till then, a simple object can represent it. This simple object is called the “Proxy” for the complex objectThe cases can be innumerable why we can use the proxy. Let’s take a scenario. Say, we want to attach an image with the email. Now, suppose this email has to be sent to 1 lakh consumers in a campaign. Attaching the image and sending along with the email will be a very heavy operation. What we can do instead is, send the image as a link to one of the servlet. The place holder of the image will be sent. Once the email reaches the consumer, the image place holder will call the servlet and load the image at run time straight from the server.Let’s try and understand this pattern with the help of a non-software example as we have tried to do throughout this article.Let’ say we need to withdraw money to make some purchase. The way we will do it is, go to an ATM and get the money, or purchase straight with a cheque. In old days when ATMs and cheques were not available, what used to be the way??? Well, get your passbook, go to bank, get withdrawal form there, stand in a queue and withdraw money. Then go to the shop where you want to make the purchase. In this way, we can say that ATM or cheque in modern times act as proxies to the Bank. Let’s look at the code now.Bank will define the entire method described above. There are references of classes like You (as the person who wants to withdraw money), also Account, as persons account. These are dummy classes and can be considered of fulfilling the responsibilities as described.**Bank.java**
/*** Bank.java* The class acts as the main object for which * the proxy has to be created. As described, going* to bank for withdrawal is very costly time wise.*/
public class Bank {
private int numberInQueue;
/*** Method getMoneyForPurchase* This method is responsible for the entire banking* operation described in the write-up*/
public double getMoneyForPurchase(double amountNeeded) {

// get object for person
You you = new You(“Prashant”);
// get obj for account
Account account = new Account();
// get person’s account number
String accountNumber = you.getAccountNumber();
// passbook got.
boolean gotPassbook = you.getPassbook();
// get number in queue
int number = getNumberInQueue();

// the number will decrease every few mins
while (number != 0) {
number–;
}
// now when the number = 0, check if balance is sufficient
boolean isBalanceSufficient = account.checkBalance(accountNumber, amountNeeded);
if(isBalanceSufficient)
return amountNeeded;
else
return 0;
}
/*** returns the number in the queue*/
private int getNumberInQueue() {
return numberInQueue;
}
}// End of class
Also, the second class is ATMProxy. This also defines the way the transaction can be handled for withdrawal of money.
**ATMProxy.java**
public class ATMProxy {
/*** Method getMoneyForPurchase* This method is responsible for the entire banking* operation described in the write-up*/
public double getMoneyForPurchase(double amountNeeded) {
// get obj of You to get card
You you = new You(“Prashant”);
// get obj for account
Account account = new Account();
boolean isBalanceAvailable = false;
// if card there, go ahead
if(you.getCard()) {
isBalanceAvailable = account.checkBalance(you.getAccountNumber(), amountNeeded);
}
if(isBalanceAvailable)
return amountNeeded;
else
return 0;
}
}// End of classHere, we can also create another proxy called ChequeProxy. I am not creating it here as the message I wanted to send across has been conveyed with the help of one proxy only. We can see here that creation of object of Bank is very costly, effort and time wise, and so, we can as well use a proxy called ATM to get the result. ATM can internally communicate with the Bank object. So, ATM here is also acting like a façade. This might and might not happen. It can happen that we at a later stage have to create the same heavy object. We just want to postpone the creation of object to the last minute so that the application is not loaded by resources utilized for creating the object.Structural Patterns – Flyweight PatternThe pattern here states about a mechanism by which you can avoid creating a large number of object instances to represent the entire system. To decide if some part of your program is a candidate for using Flyweights, consider whether it is possible to remove some data from the class and make it extrinsic. If this makes it possible to reduce greatly the number of different class instances your program needs to maintain, this might be a case where Flyweights will help.The typical example you can see on this in every book will be of folders. The folder with name of each of the company employee on it, so, the attributes of class Folder are: ‘Selected’ , ‘Not Selected’ and the third one is ‘employeeName’. With this methodology, we will have to create 2000 folder class instances for each of the employees. This can be costly, so we can create just two class instances with attributes ‘selected’ and ‘not selected’ and set the employee’s name by a method like:
setNameOnFolder(String name);This way, the instances of class folder will be shared and you will not have to create multiple instances for each employee.Creational PatternsAll the creational patterns define the best possible way in which an object can be instantiated. These describes the best way to CREATE object instances.There are five types of Creational Patterns.Factory PatternAbstract Factory PatternBuilder PatternPrototype PatternSingleton PatternCreational Patterns – Singleton PatternThere are some instances in the application where we have to use just one instance of a particular class. A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance. We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is started.
Example: We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues.public class Singleton {
private static Singleton singleInstance;
private Singleton() {}
public static Singleton getSingleInstance() {
if (singleInstance == null) {
synchronized (Singleton.class) {
if (singleInstance == null) {
singleInstance = new Singleton();
}
}
}
return singleInstance;
}Creational Patterns – Prototype PatternThe prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface Cloneable and call its method clone() to clone the object.class Bike implements Cloneable {
private int gears;
private String bikeType;
private String model;
public Bike() {
bikeType = “Standard”;
model = “Leopard”;
gears = 4;
} public Bike clone() {
return new Bike();
}
public void makeAdvanced() {
bikeType = “Advanced”;
model = “Jaguar”;
gears = 6;
}
public String getModel(){
return model;
}
} public class Workshop {
public Bike makeJaguar(Bike basicBike) {
basicBike.makeAdvanced();
return basicBike;
}
public static void main(String args[]){
Bike bike = new Bike();
Bike basicBike = bike.clone();
Workshop workShop = new Workshop();
Bike advancedBike = workShop.makeJaguar(basicBike);
System.out.println(“Prototype Design Pattern: “+advancedBike.getModel());
}Creational Patterns – Factory Patternif we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.Let’s take an example to understand this pattern.
Example: Let’s suppose an application asks for entering the name and sex of a person. If the sex is Male (M), it displays welcome message saying Hello Mr.and if the sex is Female (F), it displays message saying Hello Ms.
The skeleton of the code can be given here.public class Person {
// name string
public String name;
// gender : M or F
private String gender;
public String getName() {
return name;
}
public String getGender() {
return gender;
}
}// End of class
This is a simple class Person having methods for name and gender. Now, we will have two sub-classes, Male and Female which will print the welcome message on the screen.
public class Male extends Person {
public Male(String fullName) {
System.out.println(“Hello Mr. “+fullName);
}
}// End of class

Also, the class Female
public class Female extends Person {
public Female(String fullNname) {
System.out.println(“Hello Ms. “+fullNname);
}
}// End of class
Now, we have to create a client, or a SalutationFactory which will return the welcome message depending on the data provided.
public class SalutationFactory {
public static void main(String args[]) {
SalutationFactory factory = new SalutationFactory();
factory.getPerson(args[0], args[1]);
}
public Person getPerson(String name, String gender) {
if (gender.equals(“M”))
return new Male(name);
else if(gender.equals(“F”))
return new Female(name);
else
return null;
}
}// End of classThis class accepts two arguments from the system at runtime and prints the names.
Running the program:
After compiling and running the code on my computer with the arguments Prashant and M:
java Prashant M
The result returned is: “Hello Mr. Prashant”.When to use a Factory Pattern?The Factory patterns can be used in following cases:When a class does not know which class of objects it must create.A class specifies its sub-classes to specify which objects to create.In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.Creational Patterns – Abstract Factory PatternThis pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes.Let’s understand this pattern with the help of an example.
Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for.
The different parts of computer are, say Monitor, RAM and Processor. The different types of computers are PC, Workstation and Server.
So, here we have an abstract base class Computer.public abstract class Computer {
/*** Abstract method, returns the Parts ideal for* Server* @return Parts*/
public abstract Parts getRAM();
/*** Abstract method, returns the Parts ideal for* Workstation* @return Parts*/
public abstract Parts getProcessor();
/*** Abstract method, returns the Parts ideal for* PC* @return Parts*/
public abstract Parts getMonitor();
}// End of class
This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The specification of Parts will be different for different types of computers. Let’s have a look at the class Parts.
public class Parts {
/** specification of Part of Computer, String*/
public String specification;
/*** Constructor sets the name of OS* @param specification of Part of Computer*/
public Parts(String specification) {
this.specification = specification;
}
/*** Returns the name of the part of Computer** @return specification of PartofComputer, String*/
public String getSpecification() {
return specification;
}
}// End of class

And now lets go to the sub-classes of Computer. They are PC, Workstation and Server.
public class PC extends Computer {
/*** Method over-ridden from Computer, returns the Parts ideal for* Server* @return Parts*/
public Parts getRAM() {
return new Parts(“512 MB”);
}
/*** Method over-ridden from Computer, returns the Parts ideal for* Workstation*@return Parts*/
public Parts getProcessor() {
return new Parts(“Celeron”);
}
/*** Method over-ridden from Computer, returns the Parts ideal for* PC* @return Parts*/
public Parts getMonitor() {
return new Parts(“15 inches”);
}
}// End of class

public class Workstation extends Computer {
/*** Method over-ridden from Computer, returns the Parts ideal for* Server* @returnParts*/
public Parts getRAM() {
return new Parts(“1 GB”);
}
/*** Method over-ridden from Computer, returns the Parts ideal for*Workstation*@return Parts*/
public Parts getProcessor() {
return new Parts(“Intel P 3”);
}
/** Method over-ridden from Computer, returns the Parts ideal for* PC* @return Parts*/
public Parts getMonitor() {
return new Parts(“19 inches”);
}
}// End of class

public class Server extends Computer{
/*** Method over-ridden from Computer, returns the Parts ideal for* Server* @returnParts*/
public Parts getRAM() {
return new Parts(“4 GB”);
}
/*** Method over-ridden from Computer, returns the Parts ideal for* Workstation*@return Parts*/
public Parts getProcessor() {
return new Parts(“Intel P 4”);
}
/*** Method over-ridden from Computer, returns the Parts ideal for* PC* @return Parts*/
public Parts getMonitor() {
return new Parts(“17 inches”);
}
}// End of class
Now let’s have a look at the Abstract factory which returns a factory “Computer”. We call

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *