Post

工厂模式

工场模式

将使用者和具体类型之间的耦合隔离。面对一个经常可能变化的类型,过紧的耦合可能导致 整体的关系脆弱。

factory method将创建具体的类延迟到了子类,从而实现了扩展,解决了耦合的关系。缺点在于 要求创建方法和参数相同

比如说现在有一个划分器的需求,针对不同的类别需要不同的划分器.假设一个回调需要一个 spliter,就可以如下实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class ISplitter{
public:
    virtual void split()=0;
    virtual ~ISplitter(){}
};

class BinarySplitter : public ISplitter{
    
};

class TxtSplitter: public ISplitter{
    
};

class PictureSplitter: public ISplitter{
    
};

class VideoSplitter: public ISplitter{
    
};


class EventCallback{
  AbstractFd fd_;
 public:
  void OnConnectCallback() {
    // 这里就严重依赖到具体的类
    Isplitter* split = new BinarySplitter();
    spliter->Split(fd_);    
  }
};

加入abstract fd不断的变得话,这里得代码就不太好写。此时考虑加入factorymethod

1
2
3
4
5
6
7
8
9
10
11
class ISplitter {
  virtual ISplitter() = 0;
  virtual ~ISplitter() {}
};


class SplitterFactory {
  virtual ISplitter* CreateSplitter() = 0;
  virtual ~SplitterFactory() {}
}

针对具体的类,可以继承ISplitter,完成concret Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class BinarySplitter : public ISplitter{
    
};

class TxtSplitter: public ISplitter{
    
};

class PictureSplitter: public ISplitter{
    
};

class VideoSplitter: public ISplitter{
    
};

// 具体工厂
class BinarySplitterFactory: public SplitterFactory{
public:
    virtual ISplitter* CreateSplitter(){
        return new BinarySplitter();
    }
};

class TxtSplitterFactory: public SplitterFactory{
public:
    virtual ISplitter* CreateSplitter(){
        return new TxtSplitter();
    }
};

class PictureSplitterFactory: public SplitterFactory{
public:
    virtual ISplitter* CreateSplitter(){
        return new PictureSplitter();
    }
};

class VideoSplitterFactory: public SplitterFactory{
public:
    virtual ISplitter* CreateSplitter(){
        return new VideoSplitter();
    }
};


然后剩下的实现:

1
2
3
4
5
6
7
8
9
10
11
class EventCallback{
  SplitterFactory factory_;
  AbstractFd fd_;
 public:
  EventCallback(SplitterFactory* factory): factory_(factory) {}
  void OnEventCallback() {
    Isplitter* splitter = factory->CreateSplitter();
    splitter->Split(fd_);
  }

};
This post is licensed under CC BY 4.0 by the author.

Trending Tags