Tag: Java

behavioral pattern, Java, OOP, Strategy

Design Patterns: Strategy

The Strategy design pattern belongs to Behavioral family. It helps us to change behavior at runtime. The definition from Gang of Four book is following.
[quote name=”Gang of Four”]Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from client that use it.[/quote]

When do we have to use it

  • We use Strategy pattern when we need to hide the implementation of an algorithm.
  • When we have many related classes which differ in their behavior providing a way to configure another class with one of many behaviors.
  • Using Strategy we avoid to expose the complexity of an algorithm.
  • If you have many conditionals in front of you, and each one contains different behaviors of a class, then it is time to use Strategy pattern.

How do I use it

The Strategy design pattern is really easy to use. We just need to provide an Interface. This Interface is going to be used creating multiple implementations of different algorithms.
After implementing our algorithms we just need to create a context (Composition) which is going to use our interface gaining access to algorithms.

Example

Supposing that we develop a game, there is a character and has two or many special powers to use.

Let’s start with the interface and its implementations.

Now we are going to create the context class.

Let’s run an example.

Output:

You can download the source code from GitHub.

Design Patterns, Flyweight, Java, OOP, structural design patterns

Design Patterns: Flyweight

In this article, we are going to delve into another Structural Pattern and it is called Flyweight. Let’s start with the definition from Gang of Four Book.

[quote name=”GoF”]Facilitates the reuse of many fine-grained objects, making the utilization of large numbers of objects more efficient.[/quote]

Flyweight pattern is used to reduce the number of objects that are created. So, memory usage is decreased as well. Apart from that, a new keyword is not needed in order to create the same object again and again.

Every time that an object is created, it is stored, and if the same object is asked, then Flyweight gives it back to you. Otherwise, a new object is created and stored for future usage.

This pattern uses intrinsic and extrinsic properties.

What are intrinsic and extrinsic properties

Intrinsic properties help us make the object unique, whereas extrinsic properties are set by the client to perform a specific operation.

When do we have to use Flyweight Pattern

In case that we need to create many objects that are very similar and these objects cost a lot to be generated, it is a very good opportunity to reduce memory and increase performance by using the Flyweight Pattern.

Example

Let’s suppose that we are making a platform game. The star of the game has to kill all the enemies. Enemies are generated at the run time and they are very similar.

Using the new keyword in order to create a new enemy at the run time is too expensive. Our game is going to lack in memory and become slow if we are not careful.

It is time to create some enemies with the Flyweight design pattern.

We start with the Enemy interface.

The Next class implements the Enemy interface.

Let’s create different types of weapons.

It is time to create a Factory class. This class returns an existing enemy if an enemy of a given type exists. Otherwise, it creates a new enemy, stores it in hashTable for future usage, and returns it.

Let’s run an example.

Output:

You can download the source code from GitHub.

Design Patterns, Java, OOP, Programming, Proxy, structural design patterns

Design Patterns: Proxy

Hi guys, Today’s pattern is named Proxy and comes under the Structural family’s patterns.

This design pattern helps us to surrogate another object in order to change and control its behavior.

The definition of Proxy design pattern from the GoF book.

Provide a surrogate or placeholder for another object to control access to it.

The Proxy design pattern is very easy in use. We can use it in many ways, creating an expensive object on-demand, controlling access to the original object, and performing additional actions when an object is accessed.

Create an object on demand

Sometimes, we need to create an object only if it is necessary especially in the case that object is expensive. So, we don’t want to load it in memory until the first access.

Control access to an object

We can use it easily in order to control access to an object. For example, we want to provide full access to an object if the user is the Admin and a partially access when it is a simple user. Hold on, you will see an example using control access in a while.

Additional actions in object

Last but not least, we can use a proxy design pattern in order to add new actions to an object. For example, we can create a new instance of an object and lock this object behavior in order to be sure that no one can change its behavior.

Example

Let’s suppose that we have a system and there is a need to have users with privileges. The admin user is able to use all functionalities even delete, and a simple user has limited access to those functionalities.

We start creating an interface in order to define the commands.

Let’s implement those commands.

It is time to provide the right privileges to each user.

Create an example using the classes above.

Output:

You can download the source code from GitHub.

bridge

Design Patterns: Bridge

One more design pattern, which is lying under the Structural Patterns family, is named Bridge.

Let’s see the Bridge definition as expressed from the GoF book.

Decouple an abstraction from its implementation so that the two can vary independently.

Abstraction

Let’s start analyzing abstraction to gain insight into the Bridge pattern. When we talk about abstraction we mean that we want to hide the mechanism and the details of how something is implemented. We don’t need to be aware of how something works in-depth, we just want to use it in order to do something.

For example, we use our smartphones in order to make a call, we don’t really care how the phone works internally and we don’t need to know that. We just need to get something done and in this case, it’s just to make a call.

So, abstraction hides the implementation and shows only the general way of looking at something.

Another example is that when we use a method sort in our code we don’t really care how the algorithm is implemented, we use the sort method to sort an array of elements and that’s it (but as developers it would be better to know how it’s implemented).

Implementation

The term implementation is used in order to see what’s going on under the hood. In other words, implementation is the part that is under abstraction. It contains the code which is responsible for making an abstraction to work. It contains all the mechanisms and details to get something done.

Using the previous example, the implementation is the mechanism that takes the phone number which is typed in and makes the call true.

As we can see the relationship between abstraction and implementation is normally tight.

Now, we want to change that by making the relationship between them (objects) loosely coupled. It is time to use the Bridge design pattern.

Why do I use the Bridge Pattern?

Making objects decoupled we are able to switch implementation at run time.

We can create multiple abstractions and implementation objects and combine them independently.

Changing the implementation should have no impact on anyone.

We can share an implementation among multiple objects.

Example

In our example, we are going to demonstrate how we can decouple abstraction and implementation and how we can combine them independently without any problem.

As an example, we will use Transformers. It is easy to imagine every transformer as an entity that carries a weapon. The transformer is going to be the abstraction whilst the gun is the implementation.
Let’s see our code. Starting with the Weapon interface.

Continuing with an abstract class named Transformer.

Let’s run our code using the following function.

Output:

You can download the source code from GitHub.

behavioral pattern, Design Patterns, Java, OOP, Programming

Design Patterns: Mediator

The mediator pattern belongs in the family of Behavioral Patterns. It contains the entire logic of how objects interact with each other. So, it helps us decouple objects.

What’s the problem

In case we have many objects that interact with each other, we end up with very complex and nonmaintainable code. That’s why it is a good case to use the Mediator design pattern.

There are many times that we have interaction among objects. We usually create a sufficient amount of objects allowing us to communicate with each other with the intention of building entities that act together for a specific reason.

When something happens to an object then another one has to do something or change its behavior.

Building a complex code allowing many objects (2 or more) to communicate with each other, you will end up with spaghetti code, nonmaintainable, and you will face a nightmare every time you want to find and fix a bug or to enhance the code.

This problem increases if you normally have a back and forth and complex interaction.

How do I solve this problem

The solution comes using the Mediator pattern. This pattern allows you to keep the whole logic of communication in one place (object) and every object used to interact with other objects now interacts only with the one which is aware of how to act on every occasion.

So, we can understand very quickly that objects are decoupled. The code is more simple than it used to be. That’s exactly what we try to achieve using OOP and design patterns.

Drawbacks

Using the Mediator pattern and keeping the whole interaction among objects in one place (object) means that we are going to move complexity from one place to the other.

It is very easy to turn the Mediator pattern into a mess if you don’t separate objects appropriately. Even if you want to use the same objects but somehow different, you have to keep each behavior in separate mediator objects.

So, there is a need to simplify the mediator if necessary.

How do I code the Mediator Pattern?

It is really easy to write code with a mediator pattern.

We start with classes that encapsulate mediators and instead of interacting with each other, they interact with the mediator.

Every time each class needs to interact with an object, it calls a method from the mediator and only the mediator knows what object needs to be called.

For the mediator, we just need an interface. It is a good practice to use an interface or an abstract class for the mediator. In this way, you are able to have different implementation of the mediator object.

Example

Greek public services are a mess. Each time a Greek citizen needs to use a public service, he faces a huge bureaucracy. So, a citizen has to transfer and get a bunch of documents from one public service to the other. In this case the Greek citizen is the mediator. He is the one who has to go and find the right document in a group of public services. This is wrong from many aspects but it is a reality.

Let’s start our example by implementing this situation but a little differently, in the right way. Instead of using citizen as an intermediary mean, we will create a mediator which is going to be aware of all public services and how to use them. So, the citizen can go and ask the mediator for something and it is going to interact with public services (objects) for the desirable result.

In the following example, a Greek citizen who wants to start a new company is represented.

We start with an interface for the mediator.

Let’s implement this mediator.

Now it’s time to implement the objects which are going to interact with the mediator.

The following code is representing the Greek citizen.

Let’s create a function which runs the code

Output:

You can download the source code from GitHub.

composite, Design Patterns, Java, OOP, structural design patterns

Design Patterns: Composite

The Composite is another design pattern that belongs to the Structural Patterns family. We use this pattern when we want to group components inside a larger component. In other words, we can build a hierarchy of objects.

A definition by GoF:
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

A basic structure of Composite pattern:
Component

  • Declares an interface for objects in the composition.
  • Implements the default behavior for the interface common to all classes.

Leaf

  • It implements the behavior for objects in the composition.

Composite

  • It stores child components and defines the behavior for components having children.

Client

  • Manipulates objects in composition through the Component interface.

Structure

A composite pattern is made easily. We just create an interface or abstract class which is going to contain all methods for “Composite” and “Leaf” classes. Then, we just need to implement our classes which are going to contain some operations of Component.

When we use Component Pattern

We use it when we want to represent hierarchies of objects.

Example

Let’s get an example with a real hierarchy. We are going to represent the pride of lions. It is a perfect example that we can see how the hierarchy works.

So, we have an interface “Panthera” and three classes that are going to implement the Panthera interface. These classes are going to implement only some operations of the Panthera interface each time.
MaleLion and FemaleLion classes are “composite” and have children in their hierarchy.

CubLion class is a “Leaf” class because it implements only the behavior for objects in composition and it doesn’t have children objects.

Let’s start with the Panthera interface.

MaleLion FemaleLion and CubLion classes are following.

Now we are ready to build our first pride of lions.

Output:

You can download the source code from GitHub.

facade, Java, OOP, structural design pattern

Design Patterns: Facade

The facade design pattern is known as a structural design pattern.

The facade pattern is used to reduce complexity among classes. One way to achieve this goal is by providing a simplified interface to implement general facilities among objects.

That means we can use the facade in order to describe and implement the actions of objects. We can write a complex piece of code that performs an explicit task using some objects, and we are able to use this code again and again through facade without writing the same code all the time.

It is ideal to use it when we have some complex libraries which take effort to use. It provides us with a simpler interface to use those libraries without being concerned about how these libraries work internally.

Using facade, objects are decoupled, each promoting independence. It’s something like an entry point to our objects and also we are able to establish communication among them solely through the facade. That is how we can achieve decoupling.

The facade is a very easy design pattern to learn and that’s why you need to be careful using it. It is really easy to diverge from the right usage. This pattern has to be used not as a layer which handles data and takes decisions, but as a very high layer of the interface that just helps us simplify objects. For example, we need to execute a complex task that a person wants to book a flight and a hotel. If we don’t use facade, we have to implement every single task like date availability, destination, payment methods, and so on. On the other hand, using the facade, we are able to call only one method of facade class that performs all these actions for us.

How to use it

We can create an interface that is going to keep different implementations of our complex objects. Then we can communicate with these objects through the facade’s interface and the only thing that we need to be aware is to know the different implementations the interface offers us.

Example

Let’s see a real-world example. We have a web service that a user can log in and read some articles only if he has paid the subscription.

Let’s start with the user’s class.

The class which checks user’s credentials so as to give permissions to a user in the platform is the following.

The class checks if the user has paid his subscription and he is valid.

The class checks if the user has access to a specific article page.

Now the interface for the facade.

The implementation of the interface.

Facade pattern testing:

Output:

You can download the source code from GitHub.

behavioral pattern, Java, observer pattern, OOP, Programming, Software Engineering

Design Patterns: Observer

An observer is a pattern that falls under Behavioral Patterns. It is used when there is one-to-many relationships between objects. So, when an object’s state is changed then all its dependent objects are notified automatically.

When do you have to use Observer

  • When a change to one object requires to notify other objects.
  • We don’t need to be aware of how many objects need to be changed.
  • We don’t want these objects tightly coupled.

How to use it

The concept behind the Observer pattern is simple. We have a subject that is going to keep track of the observers. Every time this subject changes, all its observers are notified automatically. The subject contains some methods that allow observers to be registered or unregistered.

When the state of the subject changes then the subject has to notify all the observers which are registered.

This pattern is so flexible that sometimes we want to change this behavior and let observers ask the subject for the state and if it is changed, then the observer acts appropriately.

Example

Let’s suppose that we are at a university and we want to update every student who is registered in a course. If the student is registered in a specific course then every time the state of the course is changed, registered students will receive a notification.

Start with the Subject interface

We will implement the Subject interface.

Let’s create one more interface named Observer

StudentObserver class is going to implement the interface above.

Last but not least StudentObserver we have one more class named Email, and as you can imagine we are going to use this class so as to send emails to students.

Now we are ready to use these classes.

Output:

You can download the source code from GitHub.

behavioral pattern, Design Patterns, Java, template method

Design Patterns: Template Method

Hi guys, I am going to continue with behavioral design patterns and today I will introduce you to the Template Method pattern.

Template Method pattern provides a template method that defines a set of steps (it calls other methods) and the implementation of steps (methods) can be formed in sub-classes if a step has varied implementations. If not, then it’s a good practice to implement this step in the superclass.

According to Gang Of Four Book :

Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm structure.

As you can imagine, in order to create a template method pattern, an abstract class is mandatory. We can use an abstract class in order to create the template method with the steps, we can create steps if they are stable and also create abstract methods for steps that are changing depending on circumstances.

Why the Template Method Pattern?

  • When there is an algorithm with steps that may vary.
  •  Because we can avoid duplicate code and we can use inheritance through a subclass in order to use the same code.
  •  We can create a skeleton of an algorithm that helps us to simplify the complexity.

It is very easy to create a template design pattern, so, it would be better to continue with an example.

EXAMPLE

Let’s start with a simple example. We have some users who have access to a platform to fill out a test. After test completion, we extract some scores. So, we have to create a system that computes the score in two different scenarios.

At first, we will create an abstract class named Scoring with 3 methods. The first one is always a standard method “computeScore()” that returns the sum of the 2 other methods. The computation1() and computation2() methods are abstract and we are going to implement two different scenarios.

Let’s continue with the first scenario. We create a class Scenario1 which is a subclass of the Scoring abstract class.

Continuing with the second scenario and Scenario2 class.

As you can see, we have two totally different implementations of computation1() & computation2() methods in our classes. These computation approaches do not have an impact in real life, I just wrote the first thing that came to my mind.

Now we are ready to call these 2 classes.

Output:
The score from scenario 1 is: 70.0%
The score from scenario 2 is: 38.0%

Caveat: As you can see, we have an abstract class, and we extend this class in order to implement some methods. We are able to use another abstract class which is going to extend the first abstract class and so on.

When you catch yourself to act like that then STOP immediately or be careful. Do not use more than two abstract classes. In my opinion, do not use more than one abstract class because you are going to lose instead of gaining something from inheritance.

The reason is simple. The code becomes hard for debugging, you add more complexity and complexity is never good, difficult to maintain the code, and even more difficult to add new functionalities. Also, it’s a good practice to restrict the usage of this pattern because it doesn’t fit very well with the open/closed principle.

Also, you can read this article so as to get a better insight into why the Template Method pattern is a bad practice.

You can download the source code from GitHub.

behavioral pattern, Design Patterns, Game Development, OOP, Programming

Design patterns: State

Hi guys, I made a decision to see a different category of design patterns and this category is behavioral design patterns.

What a behavioral design pattern is. The text following is from Gang of Four.

Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. Behavioral patterns describe not just patterns of objects or classes but also the patterns of communication between them. These patterns characterize complex control flow that’s difficult to follow at run-time. They shift your focus away from the flow of control to let you concentrate just on the way objects are interconnected.

So, today we will see the State design pattern.

What a State design pattern is. The text following is from Gang of Four.

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

The state design pattern is one of those that is used widely in game development. It helps us to describe the different states of a game-changing object’s behavior but keeping objects loosely coupled.

For example, we have a character who is able to jump only if he is standing and not sitting, and he is able to sit only when he touches the ground.

If we try to implement this character’s behavior we will come out with a code of full “if,elseif” and multiple complex conditions that make our code ugly.

Let’s try to add some functionalities to our character, he is able to shoot only if he is standing or jumping but not when he is sitting.

As you can imagine our code is already quite complex and unwieldy in order to find a quick and easy way to add this functionality.

So, the code’s maintainability is almost unattainable, and also there are many bugs and unpredictable behaviors hidden.

For this reason, the State design pattern helps us to simplify our code. The code will be more readable and maintainable.

Let’s see the next example

Example

We will have a character with a gun. There will be 2 different behaviors of the gun. In this example, we will see only the gun’s behaviors.

So, the gun has 2 states. In the first one, the gun is loaded with ammo and ready to fire, and in the second one, it is empty of ammo.

Let’s start to design the code using the State pattern.

Interface GunState

Now, we will create the 2 classes that implement the GunState interface. ShotGunHasAmmo & ShotGunHasNoAmmo.

Finally, we implement the GunContext class in order to see a changed behavior when it changes state.

Run The code

Output:
Shotgun is in has ammo state
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Shotgun is shooting. Left Bulets 0
Shotgun is in empty of ammo state
Shotgun is empty!
Shotgun is empty!
Shotgun is in has ammo state
Shotgun is shooting. Left Bulets 3
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Append 2 bullets in Shotgun
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Shotgun is shooting. Left Bulets 0
Shotgun is in empty of ammo state
Shotgun is empty!
Shotgun is empty!

You can download the source code from GitHub.

Android, Game Development, Java, LibGDX, scene2d

LibGDX: Scene2d – Actors Part 1

Scene2d is a higher-level framework for creating games. It’s not mandatory to use it but sometimes it is very useful because code is more friendly and simpler. It is indicated for menu, buttons, checkboxes, etc. but it’s useful for board games, character’s equipment, and more.

Scene2d is composed of 3 classes regarding Scene2d :

  1. Actor: The Actor class is a node in the graph which has a position, rectangular size, origin, scale, rotation, and color.
  2. Group: The Group class is an actor that may have child actors.
  3. Stage: The Stage class has a camera, SpriteBatch, and a root group and handles drawing the actors and distributing input events.

The stage is a container that has and handles actors. Also, it has an action method that takes a delta time as an argument and it calls the act method of every Actor, allowing the actors to take some action based on time. As you can see act method is something like the update method that we already know.

The constructor of Stage class accepts only 2 arguments, Viewport and Batch. It doesn’t need to pass the camera because Viewport handles the camera internally. The batch argument is optional as well. The Stage class handles batch internally.

So, it doesn’t need to dispose of Batch manually because the stage will. That’s only in the case that we let Stage object to handle Batch alone. On the contrary, if we pass Batch as an argument in Stage then we have to dispose of it manually. As a rule, it’s better to let Stage object to handle batch alone.

Also, it doesn’t need to use setProjectionMatrix or batch.begin() or batch.end() manually because the Stage handles these automatically.

As a result, we have a more simple and maintainable code.

Sample Code

We will see an example with the Actors. We will start with class MyActor which “extends” Actor.

The constructor of MyActor class takes 2 arguments, a Texture and a String. Also, in the constructor, we set an event using addListener for our Actor. In case the Actor is touchable, we have to set it with the following line.

A very important notice is to call setBounds() method with the right arguments.

In this example, spritePos() is where the sprite position is changed and setBounds() method is called.

The next step is to pass our actors in Stage. Take a look at the following code.

As you can see, we have to pass Viewport as an argument in Stage and actors using addActor() method.

[fun_fact]If you don’t know how to use AssetManager & AssetDescriptors take a look in LibGDX: AssetManager[/fun_fact]

In render() method:

The act method isn’t needed in our case because we don’t use Actions in this example.

If we run the code we will see the following output:

scene2d_actor_example

Clicking each asset, we will see in console the following output:

Touch down asset with name : images/character.png
Touch down asset with name : images/null.png
Touch down asset with name : images/skeleton.png

The stage can handle events right and when we touch down any of the assets an event is triggered.
You can find the LibGDX source code in LibGDXExamples!

Design Patterns, Game Development, Java, OOP, Programming, Software Engineering

Design Patterns: Dependency Injection

What Dependency Injection is. Let’s imagine an object that does a specific function. Now let’s imagine a second object that takes the first object as an argument. This object cannot function or can function partially without the first one. When this happens, it’s called Dependency Injection.

Dependency Injection is a design pattern and we want to use it when an object is dependent on another object. Doing that, we are able to enhance our code with new functionalities without changing the existing code. So, our code is maintainable and extendable while allowing our program to be loosely coupled.

There are 3 ways to perform dependency injection.

The first one is called Constructor Injection. In this case, the class takes the dependent object through the constructor.

Sample Code:

Next is Setter Injection. In this case, a class that needs an external object to work takes it from a setter method. Thus, we can pass the dependent object as an argument only if there is a need for that. Dependency Injection is optional in this case.

Sample Code:

The third one is called Interface Injection. In this case, we create an interface class that has a function that takes as argument an object.

Sample Code:

Sample Code

It would be better if we continued with an example of how to use dependency injection.

We are going to create a character for a game who is modular and we can change various things like hair color, t-shirts, head size, etc. In our case, we will see only the head size as an example. So, the user will be able to change the character’s head to a big one or a regular one.

Let’s start with our interface class which is named Head.

The next two classes will implement the Head interface creating either a big head or a regular head.

The next step is to create a player who is going to take an object of BigHead or RegularHead classes as an argument.

Let’s start with the Player interface.

The class above implements the Player interface and it creates a player either with a big head or with a regular one, depending on the class that it will take as an argument.

Finally, we will create one more interface that we will use in order to implement Dependency Injection.

As we can see, each one of the two classes above creates a Player object depending on the argument.

The last method does a print in our screen.

Output:
Hi, I am the player with a big head !
Hi, I am the player with a regular head !

You can download the source code from GitHub.

Some Other Useful Resources

http://fabien.potencier.org/what-is-dependency-injection.html
https://www.martinfowler.com/articles/injection.html
http://www.procata.com/talks/phptek-may2007-dependency.pdf

http://www.javacreed.com/why-should-we-use-dependency-injection/
http://tutorials.jenkov.com/dependency-injection/dependency-injection-containers.html

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

Android, Game Developer, Game Development, Java, LibGDX, OOP, Programming

LibGDX: AssetManager

Assets are one of the most significant and demanding things in a game. Images, music, sounds, fonts, skins are only some of the reasons that a game may respond slow and have bad behavior if they are not set up correctly.

It is acceptable to have a small delay while the assets are loading before the game starts, but from the time that the game has started, we do not want to have a lag or a delay. If so, then we face the danger of losing our users because the game becomes frustrating to them.

So, we must be very careful on how to handle our assets in our game. It’s not the only thing that we have to take into account when we develop a game but it’s sure a very important one.

It is a heavy process creating new objects at run-time, so, if we need to create new assets and dispose of some others then we face the danger of having lags or our game freezing.

We have to be very careful when we use the keyword “new” at run-time. For example, the LibGDX framework loads an image with the code below

Creating new objects is costly and has negative consequences in run-time gaming. Generally speaking, it is a good habit to evade having big constructors, synchronization calls during object construction. Instead, we can use Weak References.

Also, there are some design patterns like object pooling and prototype which we can use in order to avoid using new” keyword so as to generate new instances. You can take a look at these design patterns here and here.

Back to our subject, LibGDX provides us with the right tools to handle and use assets as efficiently as possible.

One of these tools (class) is AssetManager. It’s only a very useful class that helps us handle our assets. Every single one of the assets is loaded in memory once and we can use them as many times as we want.

It’s the best way to handle images, music, sounds, and more. Also, you can read why and how to use AssetManager in LibGDX documentation.

  • Loading of most resources is done asynchronously, so you can display a reactive loading screen while things load.
  • Assets are reference counted. If two assets A and B both depend on another asset C, C won’t be disposed of until A and B have been disposed of. This also means that if you load an asset multiple times, it will actually be shared and only take up memory once!
  • A single place to store all your assets.
  • Allows to transparently implement things like caches.

AssetManager usage is simple enough.

The first line makes a new object of AssetManager. The second line puts the image myImage.png which is a texture in the queue.

From the time we call finishLoading(), we start the loading process of the assets. The whole program is blocked until all assets are loaded.

Caveat. Method manager.load(“…”); doesn’t load any asset, instead, it puts every asset in the queue and when we call finishLoading(), it starts loading the assets.

Method get() returns an asset and we use casting in order to set image variable with an image from the manager.

Attention! Don’t use AssetManager as static.

According to the documentation, it is bad practice to use AssetManager as static due to the different lifecycles of a static and Android Activity. This approach may lead to bugs and memory leaks.

There are two ways to load assets using AssetManager. We have already seen the first using finishLoading() function. The second is update() method. Using this function we have a better control when assets are loading. We can use it with the function getProgress() which returns a percentage of loading.

Take a look in the next example of code

It is worth noting that we don’t need to use dispose() in each Texture or any asset AssetManager handles. The code is more elegant and we don’t need to write too many lines so as to dispose of each asset individually.

This whole process is very useful and a big improvement during code execution. It’s a big improvement when we have to create new instances of an asset in run-time.

Drawing With AssetManager

Continuing, we will see how we can use AssetManager with a good structure. Also, we will draw some images on our screen.

Starting with class Assets and we will declare the images paths.

AssetDescriptors

We can use get(“asset name”) method in order to get the asset and use it. It’s not the best practice, in case we want to change an asset with another one. Then we have to change each one point that we have already declared.

Another reason is when we just have a single string in get() we cannot be aware of what type of asset the get() is going to return.

So, LibGDX offers AssetDescriptor which handles situations like that.

LibGDX API Class AssetDescriptor<T> describes an asset to be loaded by its filename, type, and AssetLoaderParameters. Instances of this are used in AssetLoadingTask to load the actual asset.

Now we are ready to create a class named AssetDescriptors and we will declare every asset.

The next step is to create the right code in order to load assets in AssetManager and draw these assets on screen.