Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the registrant of object factory mode by java

Shulou Source: shulou.com Published: 2022-06-02 02:38:20 09月29日 Update

This article is about how java implements the object factory pattern of registers. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Object factory mode

Class HK_ObjectFactory {protected: HK_ObjectFactory (); virtual ~ HK_ObjectFactory (); public: static HK_ObjectFactory& Instance (); typedef std::function InstanceFunc; public: void Register (const std::string& name, InstanceFunc); HK_Object* CreateObject (const std::string& name); public: std::unordered_map _ typeList;}

1. Provide a factory that can dynamically generate class instances; mainly provide registration mapping relationships, and ways to get examples.

Using macros to implement

# define CREATE_CLASS_HK_OBJ (className)\

HKObj_Factory.Register (# className, & className::createInstance)\

HKObj_Factory.CreateObject ("HK_Object")

2. The core implementation is the Register registration machine.

Definition:

In order to implement the object factory, you need to register the class in the factory with the registration mechanism, and take it directly from the factory when you use it.

By providing a class name, you can create an example of the class.

The idea of realization is:

Form a mapping relationship between the string of the class name and the method of creating the class example.

Std::map to store this relationship

Each class needs to provide a static creation function, mainly as a registration method, stored in map

The creation method and format of each class should be the same, so it can also be designed as a macro to implement

# define DECLARE_CLASS_HK_OBJ\

Public:\

Static HK_Object* createInstance (void);\

# define IMPLEMENT_CLASS_HK_OBJ (className)\

HK_Object* className::createInstance (void)\

{\\

Return className::getInstance ();\

}\

Thank you for reading! This is the end of the article on "how to realize the registration machine of the object factory pattern in java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Tags: Factory method object pattern register machine example content more article class name good practical function dynamic character string instance idea article time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi Shulou Information MySQL Huawei