Design Patterns · java

Abstract Factory Design Pattern

1-This pattern is one level of abstraction higher than factory pattern.
2-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.
3-we need to get the specification of various parts of a computer based on which work the computer will be used for.

public abstract class Computer {
//abstract factory class every method is factory method
	public abstract Parts getRAM();

	public abstract Parts getProcessor();

	public abstract Parts getMonitor();

	public static Computer getComputer(String computerType) {
		Computer comp = null;
		if (computerType.equals("PC"))
			comp = new PC();
		else if (computerType.equals("Workstation"))
			comp = new Workstation();
		else if (computerType.equals("Server"))
			comp = new Server();

		return comp;
	}
}
----------------------------------------------------------

public class Parts {
	public String specification;

	public Parts(String specification) {
		this.specification = specification;
	}

	public String getSpecification() {
		return specification;
	}
}
-----------------------------------------------------------
public class PC extends Computer{

	
	public Parts getRAM() {
	return new Parts("512 MB");
	}

	
	public Parts getProcessor() {
	return new Parts("Celeron");
	}

	
	public Parts getMonitor() {
		return new Parts("15 inches");
	}

}
-----------------------------------------------------------
public class Server extends Computer{


	public Parts getRAM() {
	return new Parts("4 GB");
	}

	public Parts getProcessor() {
	return new Parts("Intel P 4");
	}

	
	public Parts getMonitor() {
	return new Parts("17 inches");
	}

}
----------------------------------------------------
public class Workstation extends Computer {

	public Parts getRAM() {
		return new Parts("1 GB");
	}

	public Parts getProcessor() {
		return new Parts("Intel P 3");
	}

	public Parts getMonitor() {
		return new Parts("19 inches");
	}

}
---------------------------------------------------------
-----------------------------------------------------
public static void main(String[] args) {
		

		Computer computer = Computer.getComputer("Server");
		System.out.println("Monitor: "+ computer.getMonitor().getSpecification());
		System.out.println("RAM: " + computer.getRAM().getSpecification());
		System.out.println("Processor: "+ computer.getProcessor().getSpecification());
	}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s