Composite Pattern - Shapes Example - Java Sourcecode

Similar documents
Design Patterns. Vasileios Theodorou

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development

C18a: Abstract Class and Method

Interfaces & Generics

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Reusing Classes. Hendrik Speleers

Spring 2016 Programming Languages Qualifying Exam

Considerations. New components can easily be added to a design.

EECS2030 Week 7 worksheet Tue Feb 28, 2017

AShape.java Sun Jan 21 22:32: /** * Abstract strategy to compute the area of a geometrical shape. Dung X. Nguyen * * Copyright

INTRODUCTION TO SOFTWARE SYSTEMS (COMP1110/COMP1140/COMP1510/COMP6710)

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Inheritance and Polymorphism

Utilities (Part 3) Implementing static features

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Polymorphism CSCI 201 Principles of Software Development

Last Lecture. Lecture 26: Design Patterns (part 2) State. Goals of Lecture. Design Patterns

Inheritance (Part 2) Notes Chapter 6

Object-Oriented ProgrammingInheritance & Polymorphism

Design Patterns: State, Bridge, Visitor

CSE 143 Lecture 20. Circle

Utilities (Part 2) Implementing static features

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Inheritance and Interfaces

Programming by Delegation

Design Patterns. Definition of a Design Pattern

Fundamentals of Object Oriented Programming

Stacks and Queues. David Greenstein Monta Vista

Object- Oriented Analysis, Design and Programming

Solution register itself

Design Patterns IV. Alexei Khorev. 1 Structural Patterns. Structural Patterns. 2 Adapter Design Patterns IV. Alexei Khorev. Structural Patterns

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Design Patterns IV Structural Design Patterns, 1

public Twix() { calories = 285; ingredients = "chocolate, sugar, cookie, caramel"; }

Java Object Oriented Design. CSC207 Fall 2014

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

University of Palestine. Mid Exam Total Grade: 100

Information systems modelling UML and service description languages

Department of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Midterm Exam: 1 1/2 Hours, Open Book and Open Notes

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012

CS165 Practice Final Exam

2.1 Design Patterns and Architecture (continued)

2.1 Design Patterns and Architecture (continued)

Methods. Every Java application must have a main method.

16-Dec-10. Consider the following method:

Java exercises January François de Coligny, Nicolas Beudez

public Candy() { ingredients = new ArrayList<String>(); ingredients.add("sugar");

Java Memory Management

The most common relationships are: dependency, association, generalization, and realization.

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Java Collections Framework: Interfaces

More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014

MODULE 6q - Exceptions

Objects. say something to express one's disapproval of or disagreement with something.

Making the Java Coder More Productive Introduction to New Coding Features in JDeveloper

Extra Problems + Solutions

Chapter 9 Inheritance

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

F I N A L E X A M I N A T I O N

The collections interfaces


Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Design Patterns Cont. CSE 110 Discussion - Week 9

Inheritance Abstraction Polymorphism

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COSC 3351 Software Design. Design Patterns Structural Patterns (I)

JAVA Programming Language Homework I - OO concept

CS 11 java track: lecture 3

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

COE318 Lecture Notes Week 13 (Nov 28, 2011)

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Design Pattern: Composite

S T R U C T U R A L M O D E L I N G ( M O D E L I N G A S Y S T E M ' S L O G I C A L S T R U C T U R E U S I N G C L A S S E S A N D C L A S S D I A

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Design Patterns. Structural Patterns. Oliver Haase

CS165 Practice Final Exam Answer Key

BSc. (Hons.) Software Engineering. Examinations for / Semester 2

import org.simpleframework.xml.default; import org.simpleframework.xml.element; import org.simpleframework.xml.root;

Polymorphism: Inheritance Interfaces

Object Oriented Programming 2015/16. Final Exam June 28, 2016

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Outline. Composite Pattern. Model-View-Controller Pattern Callback Pattern

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

Array. Array Declaration:

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Object- Oriented Analysis, Design and Programming

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

5.4. Events and notifications

CSE143 Summer 2008 Final Exam Part B KEY August 22, 2008

Arrays Classes & Methods, Inheritance

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Implementing Classes, Arrays, and Assignments

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3:

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Design Patterns in C++

Transcription:

Composite Pattern - Shapes Example - Java Sourcecode In graphics editors a shape can be basic or complex. An example of a simple shape is a line, where a complex shape is a rectangle which is made of four line objects. Since shapes have many operations in common such as rendering the shape to screen, and since shapes follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all shapes uniformly. Composite Pattern - Shapes Example - Java Sourcecode In graphics editors a shape can be basic or complex. An example of a simple shape is a line, where a complex shape is a rectangle which is made of four line objects. Since shapes have many operations in common such as rendering the shape to screen, and since shapes follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all shapes uniformly. The code below illustrates the Shape Interface which defines the component interface: Shape is the Component interface public interface Shape { Draw shape on screen Method that must be implemented by Basic as well as complex shapes public void rendershapetoscreen(); Making a complex shape explode results in getting a list of the shapes forming this shape For example if a rectangle explodes it results in 4 line objects Making a simple shape explode results in returning the shape itself public Shape[] explodeshape(); The code below illustrates a Simple shape object which is a line, note that this object represents a leaf.

Line is a basic shape that does not support adding shapes public class Line implements Shape { Create a line between point1 and point2 @param point1x @param point1y @param point2x @param point2y public Line(int point1x, int point1y, int point2x, int point2y) { @Override public Shape[] explodeshape() { // making a simple shape explode would return only the shape itself, there are no parts of this shape Shape[] shapeparts = {this; return shapeparts; this method must be implemented in this simple shape public void rendershapetoscreen() { // logic to render this shape to screen The code below illustrates a complex object, which is a rectangle object. This object represents a Composite. Rectangle is a composite Complex Shape public class Rectangle implements Shape{ // List of shapes forming the rectangle // rectangle is centered around origin Shape[] rectangleedges = {new Line(-1,-1,1,-1),new Line(-1,1,1,1),new Line(-1,-1,-1,1),new Line(1,-1,1,1); @Override

public Shape[] explodeshape() { return rectangleedges; this method is implemented directly in basic shapes in complex shapes this method is implemented using delegation public void rendershapetoscreen() { for(shape s : rectangleedges){ // delegate to child objects s.rendershapetoscreen(); The code below illustrates a more complex shape object which also represents a composite import java.util.arraylist; import java.util.list; Composite object supporting creation of more complex shapes Complex Shape public class ComplexShape implements Shape { List of shapes List shapelist = new ArrayList(); public void addtoshape(shape shapetoaddtocurrentshape) { shapelist.add(shapetoaddtocurrentshape); public Shape[] explodeshape() { return (Shape[]) shapelist.toarray(); this method is implemented directly in basic shapes in complex shapes this method is handled with delegation

public void rendershapetoscreen() { for(shape s: shapelist){ // use delegation to handle this method s.rendershapetoscreen(); The code below illustrates the Graphics Editor Driver class which represents the client. Note how the client of the composite pattern deals with all Shape objects uniformly despite the fact that some of the shapes are leafs while others are branches. import java.util.arraylist; import java.util.list; Driver Class public class GraphicsEditor { public static void main(string[] args) { List allshapesinsoftware = new ArrayList(); // create a line shape Shape lineshape = new Line(0,0,1,1); // add it to the shapes allshapesinsoftware.add(lineshape); // create a rectangle shape Shape rectangelshape = new Rectangle(); // add it to shapes allshapesinsoftware.add(rectangelshape); // create a complex shape // note that we have dealt with the complex shape // not with shape interface because we want // to do a specific operation // that does not apply to all shapes ComplexShape complexshape = new ComplexShape(); // complex shape is made of the rectangle and the line complexshape.addtoshape(rectangelshape); complexshape.addtoshape(lineshape); // add to shapes allshapesinsoftware.add(complexshape);

// create a more complex shape which is made of the // previously created complex shape // as well as a line ComplexShape verycomplexshape = new ComplexShape(); verycomplexshape.addtoshape(complexshape); verycomplexshape.addtoshape(lineshape); allshapesinsoftware.add(verycomplexshape); rendergraphics(allshapesinsoftware); // you can explode any object // despite the fact that the shape might be // simple or complex Shape[] arrayofshapes = allshapesinsoftware.get(0).explodeshape(); private static void rendergraphics(list shapestorender){ // note that despite the fact there are // simple and complex shapes // this method deals with them uniformly // and using the Shape interface for(shape s : shapestorender){ s.rendershapetoscreen(); Alternative Implementation Note that in the previous example there were times when we have avoided dealing with composite objects through the Shape interface and we have specifically dealt with them as composites (when using the method addtoshape()). To avoid such situations and to further increase uniformity one can add methods to add, remove, as well as get child components to the Shape interface. The UML diagram below shows this The code below shows the alternative implementation for the Shape interface Shape is the Component interface public interface Shape {

Draw shape on screen Method that must be implemented by Basic as well as complex shapes public void rendershapetoscreen(); Making a complex shape explode results in getting a list of the shapes forming this shape For example if a rectangle explodes it results in 4 line objects Making a simple shape explode results in returning the shape itself public Shape[] explodeshape(); Although this method applies to composites only it has been added to interface to enhance uniformity @param shape public void addtoshape(shape shape); Although the previous code enhances uniformity but it creates a problem. How does a simple shape implement methods like addtoshape and remove from shape? There are two possibilities; one possibility is to leave the implementation empty and let the method fail silently. An alternative implementation is to throw a runtime exception if the program (or the user in case of a graphics editor) tries to add a shape to a basic shape. The code below shows this alternative implementation for the addtoshape method of the Line class. Line is a basic shape that does not support adding shapes public class Line implements Shape { // same as previous implementation Implementation of the add to shape method @param shape public void addtoshape(shape shape){ throw new RuntimeException("Cannot add a shape to simple shapes...");