-
Notifications
You must be signed in to change notification settings - Fork 1
/
interface_segregation_principle.cpp
78 lines (64 loc) · 1.56 KB
/
interface_segregation_principle.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/***
Acknowledagement: This is a lecture note for course https://www.udemy.com/course/patterns-cplusplus/ by
@Dmitri Nesteruk
Title: Interface segregation principle
Task: Clients should not be forced to depend upon interfaces that they do not use.
Avoid stuffing too much into a single interface.
Shiyu Mou
***/
#include <vector>
struct Document;
/*** bad interface, all subclass will has these 3 functions but usually only
one is needed. You have to leave the rest as empty or throw exceptions ***/
//struct IMachine
//{
// virtual void print(Document& doc) = 0;
// virtual void fax(Document& doc) = 0;
// virtual void scan(Document& doc) = 0;
//};
//
//struct MFP : IMachine
//{
// void print(Document& doc) override;
// void fax(Document& doc) override;
// void scan(Document& doc) override;
//};
// 1. Recompile
// 2. Client does not need this
// 3. Forcing implementors to implement too much
/*** better interface, seperate them ***/
struct IPrinter
{
virtual void print(Document& doc) = 0;
};
struct IScanner
{
virtual void scan(Document& doc) = 0;
};
struct Printer : IPrinter
{
void print(Document& doc) override;
};
struct Scanner : IScanner
{
void scan(Document& doc) override;
};
struct IMachine: IPrinter, IScanner
{
};
struct Machine : IMachine
{
IPrinter& printer;
IScanner& scanner;
Machine(IPrinter& printer, IScanner& scanner)
: printer{printer},
scanner{scanner}
{
}
void print(Document& doc) override {
printer.print(doc);
}
void scan(Document& doc) override;
};
// IPrinter --> Printer
// everything --> Machine