Tagged: object-oriented

Design Patterns: Abstract Factory

I’m trying to keep up the tempo and do a pattern a day, so here goes another one! Today it’s abstract factory. I wrote a post about the factory method yesterday and this one (as you can guess) is somewhat similar.

What exactly is an abstract factory? It’s from the creational patterns group, so it controls object creation. The intent is to abstract creating whole families of objects without specifying concrete classes. We have a class called abstract factory that controls the creation. The class is abstract, because it has only virtual methods. This interface is later implemented by concrete factory classes. These object factories then creates a matching set of objects under some circumstances.

Take this for instance, you have a certain set of objects, that works on Windows and a certain set of objects, that does the same job, but under Linux. In this case there will be two subclasses of the abstract factory class. One that will create objects for windows and the second one for Linux. At the runtime, you create an instance of either one, depending on what platform is the program running on and the factory will build the appropriate set of objects.

More in-depth explanation is here. I’m trying to focus at the code examples:

User Interface Example with Gimp

The code is not as straight-forward as the previous, I’ll try to explain it with some more detail. I used a picture of GIMP UI to illustrate better what I mean, but this has absolutely nothing to do with the GIMP’s code and how it’s implemented!

Gimp UI

Gimp User Interface Example

So take this for instance. Your task is to write user interface for a program. The interface design says, there will be three windows (like there are in gimp). Also, among the requirements, there is one that says your code has to work natively with both — KDE and Gnome desktop environments. Each of these is built on a different toolkit. KDE uses Qt, Gnome uses Gtk. So somewhere in your code, you’ll need to check, what environment is available and construct an object, that will work with the current environment. This is where the abstract factory comes handy.

You will encapsulate the creation of all the UI components (in this case the three windows) into the abstract factory. Abstract factory is a class, something like this:

class UIFactory
{
    virtual void Window* getToolboxWindow() = 0;
    virtual void Window* getMainWindow() = 0;
    virtual void Window* getLayersWindow() = 0;
};

It’s an abstract class — it says, “I can get you the user interface”, but it doesn’t say how or what exactly are you going to recieve. Then, for each case (in our example it’s Qt and Gtk), there will be a subclass that implements this abstract factory, saying “from me, you’re going to get Qt/Gtk windows”. Then in your program, you check what your environment is and create an instance of QtUIFactory or GtkUIFactory. At this point you can be sure, that all windows will be constructed with support of the correct environment.

C++

Here is the implementation of the above in C++.

class Window
{
    protected:
        int width;
        int height;
        std::string toolkit;
        std::string type;

        Window(std::string usedToolkit, std::string windowType)
            : toolkit(usedToolkit), type(windowType)
        {}

    public:
        std::string getToolkit();
        std::string getType();
};

class GtkToolboxWindow : public Window
{};

class GtkLayersWindow : public Window
{};

class GtkMainWindow : public Window
{};


class QtToolboxWindow : public Window
{};

class QtLayersWindow : public Window
{};

class QtMainWindow : public Window
{};

/* This is the abstract factory. */
class UIFactory
{
    public:
        virtual Window* getToolboxWindow() = 0;
        virtual Window* getLayersWindow() = 0;
        virtual Window* getMainWindow() = 0;

};

/* Factory for Gtk toolkit */
class GtkUIFactory : public UIFactory
{
    public:
        Window* getToolboxWindow()
        {
            return new GtkToolboxWindow();
        }

        Window* getLayersWindow()
        {
            return new GtkLayersWindow();
        }

        Window* getMainWindow()
        {
            return new GtkMainWindow();
        }
};

/* Factory for Qt toolkit */
class QtUIFactory : public UIFactory
{
    public:
        Window* getToolboxWindow()
        {
            return new QtToolboxWindow();
        }

        Window* getLayersWindow()
        {
            return new QtLayersWindow();
        }

        Window* getMainWindow()
        {
            return new QtMainWindow();
        }
};

int main()
{
    UIFactory* ui = 0;

    /* Check what environment is running
and create appropriate factory. */
    if (/* Gtk == */ true)
    {
        ui = new GtkUIFactory();
    }
    else
    {
        ui = new QtUIFactory();
    }

    /* Use the factory to build interface. */
    Window* toolbox = ui->getToolboxWindow();
    Window* layers = ui->getLayersWindow();
    Window* main = ui->getMainWindow();

    /* See what have we recieved. */
    std::cout << toolbox->getToolkit() << ":"
              << toolbox->getType() << std::endl;

    std::cout << layers->getToolkit() << ":"
              << layers->getType() << std::endl;

    std::cout << main->getToolkit() << ":"
              << main->getType() << std::endl;
}

The code has been shortened a little. The fully working source file is available, as per ushe at github.

Python

And here is the Python version.

class Window:
    __toolkit = ""
    __purpose = ""

    def __init__(self, toolkit, purpose):
        self.__toolkit = toolkit
        self.__purpose = purpose

    def getToolkit(self):
        return self.__toolkit

    def getType(self):
        return self.__purpose

class GtkToolboxWindow(Window):
    def __init__(self):
        Window.__init__(self, "Gtk", "ToolboxWindow")

class GtkLayersWindow(Window):
    def __init__(self):
        Window.__init__(self, "Gtk", "LayersWindow")

class GtkMainWindow(Window):
    def __init__(self):
        Window.__init__(self, "Gtk", "MainWindow")


class QtToolboxWindow(Window):
    def __init__(self):
        Window.__init__(self, "Qt", "ToolboxWindow")

class QtLayersWindow(Window):
    def __init__(self):
        Window.__init__(self, "Qt", "LayersWindow")

class QtMainWindow(Window):
    def __init__(self):
        Window.__init__(self, "Qt", "MainWindow")

# Abstract factory class
class UIFactory:
    def getToolboxWindow(self): pass
    def getLayersWindow(self): pass
    def getMainWindow(self): pass

class GtkUIFactory(UIFactory):
    def getToolboxWindow(self):
        return GtkToolboxWindow()

    def getLayersWindow(self):
        return GtkLayersWindow()

    def getMainWindow(self):
        return GtkMainWindow()

class QtUIFactory(UIFactory):
    def getToolboxWindow(self):
        return QtToolboxWindow()

    def getLayersWindow(self):
        return QtLayersWindow()

    def getMainWindow(self):
        return QtMainWindow()

if __name__ == "__main__":
    gnome = True
    kde   = not gnome

    # What environment is available?
    if gnome:
        ui = GtkUIFactory()
    elif kde:
        ui = QtUIFactory()

    # Build the UI
    toolbox = ui.getToolboxWindow()
    layers  = ui.getLayersWindow()
    main    = ui.getMainWindow()

    # Let's see what have we recieved
    print "%s:%s" % (toolbox.getToolkit(), toolbox.getType())
    print "%s:%s" % (layers.getToolkit(), layers.getType())
    print "%s:%s" % (main.getToolkit(), main.getType())

The whole thing at github.

Sources

Design Patterns: Singleton

Let’s start with something simple. Singleton is probably the most basic design pattern. When someone explains design patterns, you can be sure, that at some point he will mention this one — the singleton.

I won’t go through the whole theory, there are a way to many good sources, that explain singleton well already. I’ll just focus on the code. So, we want to have a single, one and only globally accessible instance of a certain class in our program. There are couple steps we need to do:

  • Have some place to store the instance — static variable.
  • Have some way of globally accessing the instance — static method.
  • Prevent any other way of instantiation the class — disable constructor.

C++

Implementation in C++ is pretty straight-forward. All the tasks mentioned above are easy to achieve with C++. Here is the code:

class Singleton
{
    private:
        /* Here will be the instance stored. */
        static Singleton* instance;

        /* Private constructor to prevent instantiation. */
        Singleton();

    public:
        /* Static access method. */
        static Singleton* getInstance();
};

/* Null, because instance will be initialized on demand. */
Singleton* Singleton::instance = 0;

Singleton* Singleton::getInstance()
{
    if (instance == 0)
    {
        instance = new Singleton();
    }

    return instance;
}

Singleton::Singleton()
{}

You can download the whole code here.

Python

In Python situation gets a little bit stickier, but it’s not that hard to produce a singleton class as well. The problem is, that there’s no such a thing as private constructor in Python. So, you need to find another way of preventing multiple instantiation of the class. This can be achieved by raising and exception in constructor which works good, but some might not consider that a good practice since exceptions should be use only for errors. Let’s have look at the code:

class Singleton:
    # Here will be the instance stored.
    __instance = None

    @staticmethod
    def getInstance():
        """ Static access method. """
        if Singleton.__instance == None:
            Singleton()
        return Singleton.__instance

    def __init__(self):
        """ Virtually private constructor. """
        if Singleton.__instance != None:
            raise Exception("This class is a singleton!")
        else:
            Singleton.__instance = self

Again, you can get the whole thing here.

Sources

Static variables and methods in Python

How to declare a data member or a method static in Python? Static means, that the member is on a class level rather on the instance level. Static variables exist only in single instance per class and are not instantiated. If a static variable is changed in one instance of the class, the change will affect its value in all other instances.

Static methods don’t refer to any instance of the class and can be called outside of it. They also cannot access any non-static data members of the class for obvious reasons. Let’s have a look how to get some static from Python.

Variables

All variables defined on the class level in Python are considered static. See this example:

class Example:
    staticVariable = 5

# Access through class
print Example.staticVariable  # prints 5

# Access through instance
instance = Example()
print instance.staticVariable # still 5

# Change within instance
instance.staticVariable = 6
print instance.staticVariable # 6
print Example.staticVariable  # 5

# Change through class
Example.staticVariable = 7
print instance.staticVariable # still 6
print Example.staticVariable  # now 7

Seems pretty straight-forward to me. Only confusion might come from the fact, that you can have two different variables in your class under the same name (one static and one ordinary). But I recommend (for your own sakes) to avoid that behavior entirely.

Methods

With static methods it gets a little more complex. In Python, there are two ways of defining static methods within a class.

@staticmethod

Method decorated with this decorator shares with the class only the namespace. Note that, no arguments are mandatory in the method definition. Static method can access classes static variables. See in the following example:

class Example:
    name = "Example"
    @staticmethod
    def static():
        print "%s static() called" % Example.name

class Offspring1(Example):
    name = "Offspring1"

class Offspring2(Example):
    name = "Offspring2"
    @staticmethod
    def static():
        print "%s static() called" % Offspring2.name

Example.static()    # prints Example
Offspring1.static() # prints Example
Offspring2.static() # prints Offspring2

@classmethod

The difference between class method and static method in Python is, that class method recieves one mandatory argument — a class name it was called from. Let’s have a look:

class Example:
    name = "Example"
    @classmethod
    def static(cls):
        print "%s static() called" % cls.name

class Offspring1(Example):
    name = "Offspring1"
    pass

class Offspring2(Example):
    name = "Offspring2"
    @classmethod
    def static(cls):
        print "%s static() called" % cls.name

Example.static()    # prints Example
Offspring1.static() # prints Offspring1
Offspring2.static() # prints Offspring2

Which one should you use? The first option allows you only to access the static variables in the same class. With the second approach you’ll be able to modify class variables of the subclasses without the neccessity of redefining the method when using inheritance. I prefer the first variant, because I personaly think it’s a cleaner solution, but the second variant might come useful in certain situations as well.

Sources

Private, protected and public in Python

A lot of folks learn object-oriented programming with languages like C++ and Java. And while they learn, they’re told repeatedly (over and over again), that encapsulation is one of the key principles of object-oriented paradigm and that they should take advantage of it. Sure, until you get down with Python :-).

In C++ and Java, things are pretty straight-forward. There are 3 magical and easy to remember access modifiers, that will do the job (public, protected and private). But there’s no such a thing in Python. That might be a little confusing at first, but it’s possible too. We’ll have look at how do it right in Python.

Python doesn’t have any mechanisms, that would effectively restrict you from accessing a variable or calling a member method. All of this is a matter of culture and convention.

Public

All member variables and methods are public by default in Python. So when you want to make your member public, you just do nothing. See the example bellow:

class Cup:
    color    = None
    content  = None

    def fill(self, beverage):
        content = beverage

    def empty(self):
        content = None

We have a class Cup. And here’s what we can do with it:

redCup = Cup()
redCup.color = "red"
redCup.content = "tea"
redCup.empty()
redCup.fill("coffee")

All of this is good and acceptable, because all the attributes and methods are public.

Protected

Protected member is (in C++ and Java) accessible only from within the class and it’s subclasses. How to accomplish this in Python? The answer is — by convention. By prefixing the name of your member with a single underscore, you’re telling others “don’t touch this, unless you’re a subclass“. See the example bellow:

class Cup:
    color     = None
    _content  = None  # protected variable

    def fill(self, beverage):
        _content = beverage

    def empty(self):
        _content = None

Same example as before, but the content of the cup is now protected. This changes virtually nothing, you’ll still be able to access the variable from outside the class, only if you see something like this:

cup = Cup()
cup._content = "tea"

you explain politely to the person responsible for this, that the variable is protected and he should not access it or even worse, change it from outside the class.

Private

By declaring your data member private you mean, that nobody should be able to access it from outside the class, i.e. strong you can’t touch this policy. Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into _<className><memberName>. So how to make your member private? Let’s have a look at the example bellow:

class Cup:
    _color     = None  # protected variable
    __content  = None  # private variable

    def __init__(self, color):
        _color</span> = color

    def fill(self, beverage):
        __content = beverage

    def empty(self):
        __content = None

Our cup now can be only filled and poured out by using fill() and empty() methods. Note, that if you try accessing __content from outside, you’ll get an error. But you can still stumble upon something like this:

redCup = Cup("red")
redCup._Cup__content = "tea"

This will work, except, in case you see this, you kick your colleague, who’s responsible for it hard in the nuts.

Sources

Design Patterns

Another thing I’ve been avoiding for a long time is design patterns and their use in software development. Now it’s time to learn to use those things! What I intend to do is go through all of them and write an example implementation of each in C++ and Python. You’ll find links to respective posts here later.

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Patterns are often divided into three categories.

Creational Design Patterns

Creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation. Creational design patterns are further categorized into Object-creational patterns and Class-creational patterns. Where, Object-creational patterns deal with Object creation and Class-creational deal with Class-instantiation.

Structural Design Patterns

Structural Design Patterns are Design Patterns that ease the design by identifying a simple way to realize relationships between entities.

Behavioral Design Patterns

Behavioral Design Patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Sources