委派到子组件的模式 [英] Pattern for delegation to sub-component

查看:97
本文介绍了委派到子组件的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我工作的产品中,一个非常基本的场景是类的序列化。通常,要序列化的类在其子组件上调用序列化

In the product I am working, one of very basic scenario is serialization of classes. Typically a class to be serialized calls serialization on its sub-component


如果有类s.t. class
A {B; C; D;}然后A.Pack将调用B,C,D上的
函数。

e.g. if there is a class s.t. class A{B;C;D;} then A.Pack will call pack function on B,C,D.

因为有很多这样的类,相同的代码模式必须一遍又一遍地重复。
可以在模式中封装这个行为(可能使用模板和继承)

Since there are many such classes, same pattern of code has to be duplicated over and over again. Is it possible to encapsulate this behavior in a pattern (possibly using templates and inheritance)

推荐答案

做一个模板做这是使用类型列表:

The usual way of making a template do this is to use a type list:

#include <iostream>

// typelist definition
struct Empty {};

template < typename H, typename T = Empty >
struct Cons {
    typedef H head;
    typedef T tail;
};

// interfaces all items support
class IPack
{
public:
    virtual void Pack() = 0;
};

// some packable items
class Fee : public IPack
{
public:
    virtual void Pack() {
        std::cout << "Packed Fee\n";
    }
};

class Fi : public IPack
{
public:
    virtual void Pack() {
        std::cout << "Packed Fi\n";
    }
};

class Fo : public IPack
{
public:
    virtual void Pack() {
        std::cout << "Packed Fo\n";
    }
};

class Fum : public IPack
{
public:
    virtual void Pack() {
        std::cout << "Packed Fum\n";
    }
};

// these two templates create a composite IPack from a list 
// of the types of its parts
template <typename Types>
class PackList : public PackList<typename Types::tail>
{
protected:
    typedef typename Types::head Item;
    Item item;

public:
    virtual void Pack() {
        item.Pack();
        PackList<typename Types::tail>::Pack();
    }
};

template <>
class PackList<Empty> : public IPack
{
public:
    virtual void Pack() {}
};

// FeeFiFoFum is a composite of four items
class FeeFiFoFum : public PackList<Cons<Fee,Cons<Fi,Cons<Fo,Cons<Fum> > > > >
{
};

// create a FeeFiFoFum and call pack on it, which calls pack on its parts
int main ()
{
    FeeFiFoFum giant;

    giant.Pack();
}

从类型列表创建的复合体的正确实现为成员提供访问器但是这足以显示它们是如何工作的,并且打印出它包装了费,Fi,Fo和Fum,而没有指定任何行为。

Proper implementations of composites created from type lists give you accessors for the members and so on, but this is enough to show how they works, and prints out that it packed Fee, Fi, Fo and Fum without specifying any behaviour.

这篇关于委派到子组件的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆