Software Engineering

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.

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

Design Patterns, OOP, Programming, Software Engineering

The OOP Concept

Object-oriented programming (OOP) is a way of writing code based on the concept of objects. Every object has its own arguments and functions.

If there is a need to code with OOP principles then we have to be in a continuous effort trying to describe everything into objects.

Before we continue on to how we have to think when we develop with OOP I would like to give you a very basic intro about some of the principles that we have to follow in order to build better software that is maintainable and easy to improve with new functionalities.

It’s a good practice to separate the code into small blocks of code. Every single block of code must be responsible for one task only. To achieve this goal we can use functions.

A function is a block of code that executes a specific task. We have to keep in mind and not break the rule that a function must execute only one task. This is the way that the complexity of the code will be reduced making the code reusable. Also, these small blocks of code mean fewer places for bugs to hide.

A function should not exceed 25 lines. It’s rare for a function to exceed 25 lines. We don’t need to count each line of function all the time. If a function exceeds the 1/2 of the screen it means that it may perform more than one task. So, we are able to break it in two or more functions.

If we don’t break the rule that a function must perform a single task then it’s almost certain that it will not exceed the top-up limit of 25 lines.

The name of the function is an important fact as well. The name has to describe what the purpose of the function is with one, two, or more words. It such a great help for everyone to understand what a function does without the need to read a whole block of code.

I would like to continue to write about some good practices that everyone has to follow for a better quality of code. Even that, it would not be enough. The best way to learn more about that is by reading the book named Clean Code by Robert Cecil Martin.

Every developer must read this book. Before reading anything else. If you have not read the book then stop what you are doing and go for it. It’s the best book in order to set the right bases for programming.

After this short analysis on how to improve your code quality, this is the right time to talk about OOP. As I said, we have to reduce the feature that we want to build in order to describe it as an object.

In order to do that, we have to think that an object is an entity or a class. Every class contains attributes and functions.

So we have to describe and build those attributes and functions. Every function has to perform only one action of the object. Functions are able to handle these attributes and change them sometimes. Let me give you an example.

Supposing that we want to build a game with people and dogs.

A dog is an entity that has 4 legs. This is an attribute. Also, the dog can execute tasks like barking, walking, or running. These tasks are functions. And each function performs only one of these tasks. Thus, we can make a dog.

Now we want to make a man. A man is an entity again with 2 hands and 2 legs. These are attributes as well. Some of his functions are to walk, run, and talk. As before, each of the tasks that a man can perform is a function in our class.

This way of thinking seems to be easy at first but in case we have a complex problem to solve then the code’s complexity is equally important. Even though, it’s certainly an efficient style of programming to build big applications.

There are many reasons why we want to use OOP.

It’s a really efficient way to build a reusable code. It’s certainly not so easy. We have to follow some rules like the rules that I described before. Alternatively, we will end up with a spaghetti code written in a class.

Another important reason is that developers are able to collaborate with each other more efficiently without so much communication. That means that they don’t need to waste their time describing and analyze the way in which something was built or what is the way that a new feature will be built.

To be successful, we need to use design patterns. Design patterns offer solutions to problems during development. It’s a framework that helps developers solve common problems.

Moreover, design patterns are able to solve communication problems among developers. If design patterns are known among the developer’s team, productivity and effectiveness are increased.

Writing code with design patterns it’s not so easy and requires a lot of practice and study. One of the best books is Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Ralph Johnson, Richard Helm, John Vlissides.

All of the above come true through some principles. These principles are encapsulation, inheritance, and polymorphism. According to this book these principles are :

ENCAPSULATION

The result of hiding a representation and implementation in an object. The representation is not visible and cannot be accessed directly from outside the object. Operations are the only way to access and modify an object’s representation.

In other words :

Encapsulation is the process of combining data and functions into a class. Attributes of the class are kept private and there are public getter and setter methods that are provided to manipulate these attributes. Thus, encapsulation makes the concept of data hiding possible.

INHERITANCE

A relationship that defines one entity in terms of another. Class inheritance defines a new class in terms of one or more parent classes.The new class inherits its interface and implementation from its parents. The new class is called a subclass or (in C++) a derived class. Class inheritance combines interface inheritance and implementation inheritance. Interface inheritance defines a new interface in terms of one or more existing interfaces. Implementation inheritance defines a new implementation in terms of one or more existing implementations.

POLYMORPHISM

The ability to substitute objects of matching interface for one another at run-time.

This was a quick review of what OOP is. It is really an immense subject, and we only just scratched the surface of it.

I will get back to the subject soon with more details when I present design patterns.

View More