Factory Design Pattern

Manager Class : Hi, I want to create an object A.

Developer : Then you need a Factory!

Actually, the small conversation above can explain the Factory Design Pattern easily. If we want to create an object A, we need a factory that creates object A. Let’s implement our approach to Unity3d.

Scenario

Imagine that, we have a shape renderer that renders shapes. The shape renderer will have a list that contains shapes to render. Shape renderer gets shapes from Shape Factory. The previous sentence is the key of our scenario. We are going to render Sphere and Cube objects in this sample.

Ok, Let’s code.

Step 1

We are creating the Shape base class. The class has Draw() method and center point in the world.

Step 2

Let’s create Cube and Sphere objects.

Cube.cs

Cube has an additional variable named _size. In geometry, The size of the cube is Size(length, width, height).

Sphere Nesnesi

_radious is the radius of the sphere.

Cube and Sphere derived from Shape. And these classes override the Draw method.

Step 3 

Let’s create our shape factory.

We defined cube and sphere types.

Shape Factory

Now, shape factory can return a shape by shape type.

Step 5

Shape Renderer

Shape Renderer nesnesi,  Start() metodu çağrıldığında Draw() metodunu çağıracağı nesneleri, ShapeFactory’den alır ve OnDrawGizmos() metodu içinde bu nesnelerin Draw() metodlarını çağırarır.

On Start method of Shape Renderer, called Draw() methods of shape objects got from Shape Factory.

Output

You are going to see a black sphere and red cube in the scene view.

Feel free to contact me directly at cosgun.halil@gmail.com