Over a million developers have joined DZone.

Tile Flooring Problem: Usage of Chain Responsibility Design Pattern

DZone's Guide to

Tile Flooring Problem: Usage of Chain Responsibility Design Pattern

Want to learn more about using the Chain of Responsibility (CoR) design pattern in Java? Check out this fun flooring example to learn how!

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

Java design patterns have many benefits and use cases, specifically when it comes to building an application, like web-based, SDK, application services, etc. The Chain of Responsibility (CoR) is one of the most commonly used behavioral design patterns in Java. In this article, I will take a look at a problem and its relation with the CoR design pattern.

Tile Flooring Problem

Situation: There is a room (rectangular in size) floor that needs to be completely covered with tiles on the floor. So, the two variables are x and y, which are the dimensions of the room.

Given: There are tiles of various sizes, for example, 5x5, 2x2,1x1 etc. Here, it is assumed that the tile is square and not a rectangle.

Constraints: Breaking any tile to create a different size is not allowed.

Problem: Let's take 9ft and 11ft as the dimension of the room. 

5x5, 2x2, 1x1 are the dimensions of three tiles.

Image title

Now, let's find the minimum number of tiles needed to cover the room completely.

Relation With Chain of Responsibility Design Pattern

If we choose the order as fill the room with tiles that have sizes in decreasing order from highest to lowest in dimensions, then, every floor class will fill the room and pass the remaining floor dimensions to next chain.

This will continue until the chain is passed to the lowest dimension tile class (in this case, it's 1x1). Every tile class is just printing the result (one of the tiles required size x = p).

Extending the problem: We can apply many variations of this problem, like partial fill vs complete fill, etc. Some of the common extensions are:

  1. This can be extended to 3rd dimension, where cubes can be used to fill the complete room.

  2. This can be extended to rectangular shaped tiles.

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

java ,design pattens

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}