creational patterns

creational patterns, Design Patterns, Factory, Game Developer, Game Development, Java, OOP, Programming, Software Engineering

Design Patterns: Factory

The factory is one more design pattern that comes under creational patterns. Thus, this pattern is able to make our code less complex and it gives us the opportunity to get an object without using the “new” operator. The factory is quite simple in use.

The factory is used when there is a need to hide the way that an object instantiated and it’s complex or many dependencies are needed.

Also, as Head First: Design Patterns book refers

[quote name=””]Instantiation is an activity that shouldn’t always be done in public and can often lead to coupling problems.[/quote]

You can read more about this subject in the resources below.

javaworld.com

Head First: Design Patterns

Design Patterns: Elements of Reusable Object-Oriented Software

In other words, using the factory, different types of objects can be created and returned without using the “new” operator or be interested in how this object can be instantiated.

Through factory class, an instance of another class can be taken.

Sample Code

Let’s start analyzing the code below. We are going to create a character who is able to use a gun or his punches. So, we will start implementing these classes. At first, we will create an abstract class for Gun.

Next 2 classes extend from Gun abstract class. ShotGun and Punch classes.

Now we are ready to create our character with ActionFigure class.

In case that, we use constructor without any argument then our character is going to use Punch class.

Last but not least, we will create factory class that returns the desirable figure to us.

This class contains 2 functions, the first returns an instance of ActionFigure without a gun and the second with a gun.

Also, this design pattern is called Static Factory due to the static functions in factory. The advantage is that we don’t have to instantiate the factory in order to use createFigurePunch() and createFigureShotGun() functions.

The drawback is that we are not able to subclass and change createFigurePunch() and createFigureShotGun() functions behavior.

In continuing, we call and get desirable instances from factory using the code below.

Output:

Action figure without gun created!

Figure is shooting : Punch

figure is shooting 3 times :

Punch

Punch

Punch

Action figure with gun created!

Figure with gun is shooting : Gun is shooting. Left Boolets 2

Figure with gun is shooting 3 times: Gun is shooting. Left Boolets 1

Gun is shooting. Left Boolets 0

Gun is empty!

Figure with gun is shooting : Gun is empty!

Figure with gun reloads gun: Figure with a gun is shooting: Gun is shooting. Left Boolets 2

Conclusion

To sum up, factory is a design pattern easy in use and simplifies the code’s complexity a lot. Using “new” operator is definitely a bad approach and we have to avoid using it. Factory helps to write a more clear code with less bugs.

You can download the source code from GitHub.

creational patterns, Design Patterns, Game Development, Java, OOP, Software Engineering

Design Patterns: Prototype

The prototype is a design pattern that belongs in the “creational patterns” category. This pattern is used in order to avoid the usage of “new” operator, especially in the case there is a need to create new objects at run-time.

So, there is the possibility to clone an object instead of using the “new” operator in order to get a new object. This new object is very different from the initial object, but the new one keeps the state of the old object.

To be more precise, before cloning an object, we have to create one. That means we have to get an instance of the class using the new operator as it’s already known. Continuing, we are ready to get more instances of the object just by cloning it.

In order to clone an object, the object must always do implements Cloneable interface.

The advantage of using cloning is less costly than creating a new one with a “new” operator.

Also, an object which is Cloneable is able to be cloned every time during code execution. Usage of Cloneable is suggested on this occasion and can improve the execution time.

Equally important and useful is when a class consists of more than one state. So, it’s preferable to create instances for every single state and clone each one of them instead of using the “new” operator.

Continuing, we will see an example of using a prototype design pattern. You can download the source code from GitHub.

Prototype Example

We will use the same example that we used in Object Pooling design pattern.

So, we will have a class that it’s going to create a dot.

This class is named DotPrototype and implements Cloneable Interface as I said earlier.

You can see the source code of DotPrototype below.

As you can see this class takes only two arguments which depict a dot. Also, it accepts the dot’s color.

At the end of the class, there is a function named clone() which gets overridden.

This function calls parent function clone() returning a new instance of an object. In case that class doesn’t implement Cloneable interface then we get an exception message.

The next step is to create another class and we will implement all states of the DotPrototype class there. And we will put these states in a Hashtable in order to get one, easily and fast.

We are going to create 3 instances of DotPrototype and each one will have a different color. So, Hashtable is going to keep 3 instances, red dot, yellow and green dot.

Source code of DotSpawner

After that, we have to initialize DotSpawner class giving the command below.

DotSpawner is a static class.

We are almost ready, the last thing that we have to do is to call getDot(“Color that we have instantiated”) to get the desired instance and call clone().

So, we get a new different object but with the same state.

Output : 

prototype design pattern

Conclusion

In order to use the clone method, the class must implement Cloneable interface.

It’s useful to use a prototype pattern when there is a need to create new instances of an object during execution time. Also, when a class has many states to implement.

Using clone is faster than using the “new” operator.

Last but not least, you can see the resources below that I found very useful.

gameprogrammingpatterns.com

sourcemaking.com

oodesign.com

wikipedia.org

creational patterns, Design Patterns, Game Development, Java, Object Pooling, OOP, Programming

Design Patterns : Object Pooling

Object Pooling is a design pattern that belongs to creational design patterns. Creational design patterns are the ones that deal with object creation mechanism. This gives the program more flexibility in deciding which objects need to be created for a given use case.

Design pattern object pooling gives us the ability to load some instances before any object, so we are able to borrow any of the pre-loaded instances from the reusable pool class.

Using the keyword new to create multiple instances of the object every time, is costly. This cost is related to the time a new instance needs to be created.

The fact that we are able to borrow some instances of an object and return them back to the pool when we don’t need them is very useful.

Object pooling is usually used in games. For instance, in our game, there are some characters who have a gun and shoot. Every time that we use the keyword new to create a new bullet our game is becoming slower and doesn’t work as we would expect.

So, in this case, it is not only the right decision to use object pooling, but it’s mandatory.

Also, it’s a good practice to use it in our characters and some other points of our game.

Now we are ready to see a simple example of object pooling usage.

Using Object Pooling

Our game is simple, the user has to connect the dots so as to make something known to us, like an elephant, a man, flowers e.t.c.

The game is going to have a lot of levels, so, that means we will create and destroy dots all the time. So, it is a great chance to use object pooling pattern.

Let’s start with the Dot class.

As you can see this class creates only a dot. The code below creates the dot.

circle = new Ellipse2D.Float(posX, posY, radious * 2, radious * 2);

Additionally, a function named isColliding() checks if this dot intersects with a line.

The next step is to create an abstract Pool class. You can see the code below.

The constructor calls method init(). This method initializes the object with instances of Dot class.
Method addObj() is an abstract function. Also, there are 2 more methods, method size() returns the size of the object and the second removes all of the elements from objects.

DotPool class is extended by an abstract Pool class. Let’s take a look at the code :

Method addObj() adds a new instance in objects.

Method get() returns an instance of Dot if it exists, otherwise, it creates a new one. Also, it is a good practice, if there is not any available instance, to wait to get back one instead of creating a new one.

Method free(Object o) returns an instance to objects.

Last but not least, the Main class.

OUTPUT:

And this is the window that our code produces.

object pooling dot window

As you can see, Pool starts with 2 instances of Dot class. We get one instance and  1 remains in Pool. We get one more instance and we can see that size of the Pool is 0.

In the next step, we release the second instance back to the Pool, and Pool’s size is 1 again.

After that, we ask 2 more instances from Pool, but only one exists. So, Pool will create a new instance.

Now we release all the instances back to the Pool.

As you can see, Pool starts with 2 instances but in the end, it has 3. This has happened because we asked 3 instances and get() function is able to create a new instance if there is not any in Pool.

You can find the code in my GitHub account.

If there is any mistake or you have any questions, please let me know.

If you want to read more about creational patterns and object pooling you can read these books Design Patterns: Elements of Reusable Object-Oriented Software and Game Programming Patterns.

View More