Allow the flexible creation of new “classes” by creating a single class, each instance of which represents a different type of object.
In object-oriented programming the type of an object is often tied to the language to represent the structure of data. As such the types for objects are created during compilation and there are usually no convenient ways to create new types during execution of the program. As such, only a finite amount of types is available during the execution.
Consider a hierarchy of creature types in a fantasy game. There could be a humanoid class at top, from which a dwarf species might be extended. The dwarf class in turn could split into different professions, such as dwarven farmer or dwarven chef. Continuing the chain, these classes might split into further specializations or proficiencies. Should we run into a case, where one of the dwarves decides to reconsider her life choices and pick up poetry instead, we could have a slight issue. Due to limits of development time, poet variants were created only for trolls and pixies.
In such cases the type of an object needs to be attached to the class, rather than class being of a type. This is where the type object pattern comes in. Now we can create a profession type and a species type and add reference to one of each to the humanoid class. This way any humanoid can be changed to any profession (or become any species, we will list that problem under the game design choices) and entirely new professions can be created during gameplay.
In structure this pattern has certain similarity with the flyweight pattern covered on a previous week. The objects in this pattern look a lot like unshared flyweights . Each object in the pattern is composed of two classes. The typed object holds instance specific data, general behavior and a reference to the type object. Type object represents a different logical type of an object. It also implements some of the behavior, which is type specific, and holds all data that is shared across all the objects of given type.
Benefits of type object (read more):
Disadvantages of type object:
TBA
TBA