State Design Pattern - Java
Photoshop Coding Kata
Write a program to draw shapes using Photoshop. Photoshop has a Canvas. User can draw a shape by choosing a tool from the Canvas.
Canvas has the following tools as of now. Program should be flexible to add more tools.
- Tool to draw
Rectangle
- Tool to draw
Triangle
- Tool to draw
Circle
After choosing a tool, user should be able to draw respective shapes on the Canvas.
Drawing a shape consists of:
Mouse Down
at a specific point(x,y)
Mouse Drag
over the Canvas andMouse Up
on a specific point(x,y)
First Step
Write a program without using any design patterns. This is an important step. Wihout this step, if you directly jump to deisgn pattern then you will not know what problem the design pattern is solving, so do not skip this step.
As you start writing the code, you will see that lots of decisions have to me made and the code soon becomes complex to manage.
Read some theory about
State Design Pattern
just to get a high level view of how it can solve the problem. Don't worry if you don't understand it fully.
Applying State Design Pattern
- First create an
interface
having methods which are common to all the tools
// sudo code
interface Tool {
mouseDown(x,y)
mouseUp(x,y)
mouseDrag(x,y)
}
Create a
Canvas
classCanvas
class will work withTool
interface instead of the actual classes implementingTool
interface.List of concrente classes
Rectangle implemets Tool
Triangle implements Tool
Circle implements ToolSince all the tools implement the
Tool
interface, inner working details are abstracted formCanvas
class. This allows us to easily extend the program to add new tools.Give an instance of actual tool to the Canvas during run time. Ex: User selects a tool.
Create a
User
class, representing the UserUser class will have a method to select a tool ex:
selectTool(<Enum>)
. User will use the methodsmouseDown
,mouseDrag
andmouseUp
on Canvas object to draw a shape.
Which Object Oriented Principles are applied here ?
Abstraction
- Actual working details of tools are abstracted from
Canvas
.
- Actual working details of tools are abstracted from
Polymorphysim
- Same methods are used to draw different shapes. Methods draw shapes based on the tool selected. Canvas delegates the responsibility to respective tools using an interface. This is the cornerstone of building loosly coupled systems.
Open/ Closed Principle
This example also displays Open/ Closed
principle.
Open for Extension
- New functionality can be added by adding new classes and testing only those classes
Closed for Modification
- Canvas is NOT allowed to modify existing classes because they are not directly used by the Canvas. Canvas uses interface to work with them
Sequence Diagram - Draw a Rectangle
Sequence Diagram - Draw a Circle
How to run the program ?
Clone the github repository
git clone git@github.com:smarigowda/StatePatternJavaPhotoshopKata.git
Open the project in IntelliJ and run the main program