Dialogue # 12: Abstract Factory, Template Style

zhaozj2021-02-16  56

Dialogue # 12: Abstract Factory, Template Style

"We know what this is?" I pointed to the equipment on the front metal table. This is one of the first batch of objects explored under the ice origin.

Jenny shook his head. "No, guy. It may be a trophy, spacecraft propeller, children's toys, or just garbage. Last week, we have thought that it is manufactured to make energy systems, for this and other equipment, but after joining fuel Nothing happened. As the energy is far away, the technology will return to the drawing board, but they think soon can get it. "

"What?"

"hope."

I aimed at the clock on the wall. "Well, the time is almost the same. I am shaking, I am very cold. Every time we ask the Exploration Team to give us some new things to drum, they always make some new things. I really hope that I am afraid. Any one. "

"I hope we can know more about things from this 'Artifact Factory'." Jenny agreed.

"This makes me recall some of the things that have happened to me, at that time ..."

Jenny squinted her eyes. "Tell as, when can we go to a warm place."

"Bad news," I cross the partition to Wendi.

"呒?" She explored her head.

"You know what I wrote last week."

"Not very clear, talk."

I didn't care. "Well," I will continue, "I have to implement a class factory for it. Goau suggests that I will see the customer group written by the customer group."

"Well, then?" Suddenly frustrated now, she is on her face: "Hey. Bob wrote, is it?"

I nodded heavyly. "Yes, I can give him praise - whenever I open his code, I can learn something happens to be realized." Weidi haha ​​laughed with the seat.

I sighed and then the check out source. Fortunately, I don't think so bad. It's just a very large amount of IF statement nested - I have prepared it. But it is already a terrible code, so according to GURU's advice, I am going to implement an Abstract Class Factory [1]. Since there is no multi-threaded and concurrent demand, I decide to implement the factory as a Singleton mode:

Class BaseFactory

{

Typedef std :: auto_ptr (* basecreatefn) ();

Typedef st :: map fnregistry;

FnRegistry Registry;

BaseFactory () {}

BaseFactory (const basefactory &); // not userned

BaseFactory & Operator = (const basefactory &); // not userned

PUBLIC:

Static BaseFactory & Instance () {Static BaseFactory Bf; Return BF;

Bool regcreatefn (const std :: string &, basecreatefn);

Std :: auto_ptr create (const st :: string&) const;

}

Bool BaseFactory :: RegcreateFN (const st: string & classname, basecreatefn fn)

{

Registry [classname] = fn;

Return True;

}

Std :: auto_ptr BaseFactory :: Create (const st :: string & classname) Const {

Std :: auto_ptr Theobject (0);

FnRegistry :: const_iterator regentry = registry.find (classname);

IF (regentry! = registry.end ())

{

Theobject = regentry-> second ();

}

Return theobject;

}

In the implementation of the base, I join:

Namespace

{

Std :: auto_ptr createbase ()

{

Return std :: auto_ptr (new base);

}

Bool Dummy = BaseFactory :: instance (). RegcreateFN ("Base", CreateBase;

}

"Well, yes," I thought. "After registering a function to the factory, the generated instance is 1, 2, 3 is so simple."

int main ()

{

Std :: auto_ptr anObject = basefactory :: instance (). Create ("BASE");

}

I will continue to generate a derived class to test an instance through the plant. In the implementation of derived class, I join:

Namespace

{

Std :: auto_ptr createerived ()

{

Return std :: auto_ptr (new derived);

}

Bool Dummy = basefactory :: instance (). regreatefn ("derived", createerived;

}

But the compiler blocks me coldly - it prompts that CreateriveD cannot be converted to the required type. After confused, I remembered the implicitly converted to the Base to point to Base. [2]. I realized that I have encountered a compiler that I can't make implicit pointer conversion problems, so I have modified the crete function slightly:

Namespace

{

Std :: auto_ptr createerived ()

{

Return std :: auto_ptr (new derived);

}

Bool Dummy = basefactory :: instance (). regreatefn ("derived", createerived;

}

Looking back at the base class, I noticed that the registration code is almost the same, so I wrote an alternative macro:

#define register_class (base_class, derived_class) /

Namespace /

{/

Std :: auto_ptr create ## derived_class () /

{/

Return std :: auto_ptr (new derived_class); /

} /

Bool Dummy = BaseFactory :: instance (). regreatefn (/

#Derived_class, create ## derived_class; /

}

Use this macro very simple:

Register_class (base, base)

"The work in nearly an hour is doing well," I muttered when I was completed.

"Yes, it is true, my child. But you can do better." Guru gentle voice appeared behind him, I still be scared. "what-?"

"This is the macro," she explained, "is difficult to read and understand, and the macro is not type safe. Also, what is this BOOL variable?"

"This," I have some conflict, "it is the only way I can think of, I can make sure that the registration function is automatically called. I don't want to modify the code of the typical factory when I add a new class."

She nodded. "Very smart ideas, my child. However, your factory is not very common. There will be more and more needs of Abstract Factory. I expect you to create such a factory: every class level that can be applied Automatic processing, rather than requesting modification (CREATE A FACTORY THAT WILL HANDLE, NOT Require, Modification for Each Class Hierarchy It Will BE Used "

"A universal abstract factory? This is a strict, isn't it?"

"Apprentice, you never fear challenges, is it? 'Experience is by industry achieved ..."

"'... and perfect by the swift course of time'," I linked [3]. "I am not afraid of challenge, but I can't take a lot of time if I set up my schedule."

"You have already done it. What you need is to consider general," she pointed.

"Consider general ... After a few minutes, I glanced behind it, and Guru had quietly seen it as it appeared. I am a little bit, and turn back to continue.

After a while, I realized a factory template:

Template

Class GenericFactory

{

Typedef std :: auto_ptr (* basecreatefn) ();

Typedef st :: map fnregistry;

FnRegistry Registry;

GenericFactory ();

GenericFactory (const genericfactory &); // not userned

GenericFactory & Operator = (const genericfactory &); // not userned

PUBLIC:

Static GenericFactory & Instance ();

Void RegcreateFN (Const ClassIDKey &, Basecreatefn);

Std :: auto_ptr Create (const classidkey & classname) const;

}

I think that all classes use std :: string as the key value, so I use the key value type as a template parameter. The implementation of all functions is exactly the same as I wrote in BaseFactory, except that the registration function. I use a more elegant template to implement it:

Template Class RegisterInfactory

{

PUBLIC:

Static std :: auto_ptr createInstance ()

{

Return std :: auto_ptr (new manufacturedtype);

}

RegisterInfactory (Const ClassidKey & ID)

{

GenericFactory :: Instance (). Regreatefn (id, createinstance);

}

}

Now, each class derived from the base class only needs to add a line of code to get the type of security Creation function:

RegisterInfactory Registerme ("Base");

Template constructor registers its class name to Creation Registry [4].

I aim in a look, just seeing Guru came over. I smiled ;; for overce i was slightly ahead of her game At least once, I predicted her trick. "Very good, apprentice," she said behind me. "Your factory is generic, portable, not dependent on registry, DLL, or other complex tips."

"But there is still a shortcoming," I interrupt. "Because this registration behavior relies on a Static object. It must have been initialized. If you use this plant before MAIN is executed, do not guarantee all Creation functions successfully registered."

"Yes, apprentice, your factory relies on the order of static initialization, the prophet Cline explains this problem [5]." She turned away.

"Wait a minute," I shouted. Guru turned. I tried to inquire about the problem in my mind. Guru took the hair after waiting for the ear. "It is about Bob. Since he is a programmer," I tried, "how ..."

"Why is he still waiting here?" GURU lined. I nodded. Guru thought. "You pay attention to him is bustling? The supervisor thinks he has two brush, will not make mistakes. Because we ... um ... In the past, Bob made them believe that my complaint is from the disturbance of the exmanent wife. And, For him, anyone who is consistent with my opinion is involved in the conspiracy with him - his statement, not mine. "

"It's really rogue. Why do you tolerate him? You can find another work." I looked with your fingers.

She shrugged a shoulder. "In addition to Bob, I like it. In addition, if I leave, I can't enjoy this happens happily." We are all laugh. "But," said that she said, "this company has a lot of growth opportunities. For example, our new medical equipment department will need a core figure of software development - I am applying for this position."

"Great! I wish you good luck," I replied. Guru nodded. I returned to my work to complete the last part of the Abstract Factory template.

When the news came, it was a few days later. But I didn't get it until the next morning. I still sleep, I am falling into chaos, unusual noise makes me cover the ear with your hand into a group. "What happened?" I muttered to more than a dozen people who have arrived. They are happy to talk to each other. "How is it so happy in the morning?"

The competent Guilb laughed, "We think we have found it, my child, I think we have to do it." "What?" I fog.

"It seems that energy is restored," Jenny said very simple.

[Note and Reference]

[1] Gamma, Helm, Johnson, Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software (Addison Wesley, 1995).

[2] JIM HYSLOP AND HERB SUTTER. "Conversations: roots," C / C Uses Journal C Experts Forum, May 2001, http://www.cuj.com/experts/1905/hyslop.htm.

[3] William Shakespeare. Two GentleMen of Verona, I III 22.

[4] The Complete Factory File, Along With A Small Driver Program, IS Available On The Cuj Website At Hyslop.zip.

[5] Marshall Cline. C FAQ-Lite, http://www.parashift.com/c -faq-lite/.

转载请注明原文地址:https://www.9cbs.com/read-26720.html

New Post(0)