'Factory'에 해당되는 글 1건

  1. 2007.12.13 [C/C++] Use instantiate-function(factory function) to hide concreate class...

[C/C++] Use instantiate-function(factory function) to hide concreate class...

Language/C&C++ 2007.12.13 22:44
[[ blog 이사 과정에서 정확한 posting날짜가 분실됨. 년도와 분기 정도는 맞지 않을까? ]]

C++ doesn't support the 'interface' explicitly unlike Java. So, combination of abstract class and virtual function, is used.

Let's think of following case.

  A : pure abstract class (interface class).
  AImpl : implementation(concrete) class inherited from A.

External module that want to use ModuleA need to know interface, but don't need to know it's implementation. So, Knowing class A should be enough to use ModuleA. And this is tightly coupled with the way of instantiation.
Let's see below

A* instance = new AImpl(argument);

This is easy way. But, in this case, definition of 'AImpl' should be included in external code. This is not good in terms of 'Information Hiding'. We want to hide implementation details (even if it's header). See following example to do this.

----- A.h
class A // interface class
    virtual ~A(){};
    static A* Create_instance(Arguments);
    int Interface_function_A(void) = 0;
    int Interface_function_B(void) = 0;

---- AImpl.h
#include "A.h"
class AImpl : private A
    friend class A;

---- A.cpp
#include "AImpl.h"
    AImpl* instance = new AImpl(Arguments);
    return static_cast(instance);

Now, knowing definition of class A is enough to use this module. Therefore, implementation details are completely hidden. Besides, inheriting as 'private', can prevent module from unexpected usage (AImpl can be used only through A). Here is sample usage.

#include "A.h"
A* instance = A::Create_instance(Arguments);
delete instance;

We made function for create instance. But, we should make destroying instance be possible by 'delete' keyword. Because, in many cases, knowing instance's concrete class at the moment of deleting it, is not necessary. And unifying interfaces to destroy instance (into using 'delete') is also good to read.

Trackback 0 : Comment 0

티스토리 툴바