Object:: Design Patterns Capture Software Architecture and Design
Object:: Design Patterns Capture Software Architecture and Design
Theory:
Software Architecture:
Scenario
Architecture is an artifact for early analysis to make sure that a design will yield an acceptable system.
System Design is process of implementing software solution to one or more set of problem.
a) Rely on abstract class and interface to hide differences subclasses from clients
1. Creational
2. Structural
3. Behavioral
Creational Patterns
Provides a way to create objects while hiding the creation logic rather than instantiating object directly using a
new operator.
this gives more flexibility to program in deciding which objects needs to be created for a given use case.
1. Factory Pattern
2. Singleton Design Pattern
3. Builder Design Pattern
Factory Pattern
Define an inheritance for creating a single object but let subclass decide which class to instantiate
In Factory pattern, we create object without exposing the creation logic to the client and refer to
newly created object using a common interface.
Application
In our implementation the drawing framework is the client and the shapes are the products.
All the shapes are derived from an abstract shape class (or interface).
The Shape class defines the draw and move operations which must be implemented by the concrete shapes.
Let's assume a command is selected from the menu to create a new Circle.
The framework receives the shape type as a string parameter, it asks the factory to create a new shape sending
the parameter received from menu.
The factory creates a new circle and returns it to the framework, casted to an abstract shape.
Then the framework uses the object as casted to the abstract class without being aware of the concrete object
type.
Exercise
We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class
ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE
/ RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.
Step 1
Create an interface.
Shape.java
void draw();
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
@Override
Square.java
@Override
Circle.java
@Override
Step 3
Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
if(shapeType == null){
return null;
if(shapeType.equalsIgnoreCase("CIRCLE")){
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return null;
Step 4
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
shape1.draw();
shape2.draw();
shape3.draw();
}
Step 5
Verify the output.