Article 138 - Design Pattern - Flyweight Pattern Example

Design patterns were generalized to aid less experienced programmers to learn and adapt theoretical strategies into real world applications. This article goes over a flyweight design pattern example.

It is recommended that the reader review the concepts by reviewing Article 17 - Technical Interview Questions - Design Patterns.

Implementation

Definitions of Flyweight objects.

typedef struct Integer{
    int value;
} Integer;

Initialize global objects that will be used throughout life of the program.

static Integer integerZero = { 0 };
static Integer integerOne = { 1 };

This function reuses the Flyweight objects if possible. If a common integer is requested, such as 0 or 1, the global object will be used instead of generating a new object.

Integer * convertIntToInteger( int intValue ){
    Integer * integer;

    if( int == 0 ){
        return &integerZero;   
    }
    else if( int == 1 ){
        return &integerOne;
    }

    integer = (Integer *)malloc( sizeof( Integer ) );
    
    if( integer ){
        integer->value = intValue;
    }

    return 0;
}

Comments (0)

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.