将不同职责放在一起的代码。代码更短,看起来很容易使用。
// Base class.
class A
{
public:
// Native responsibility.
virtual void F();
// Show it with graphics.
virtual void ShowGraphics();
// Show it with table.
virtual void ShowTable();
// IO
virtual void Read();
virtual void Write();
};
// A number of concrete classes derive from base class.
class B : public A
{
public:
// Native responsibility.
virtual void F();
// Show with graphics.
virtual void ShowGraphics();
// Show with table.
virtual void ShowTable();
// IO
virtual void Read();
virtual void Write();
private:
// Include attributes required for native responsibility.
// Include attributes required for showing with graphics.
// Include attributes required for IO.
// Include attributes required for showing with table.
};
使用图形职责作为示例来分离职责的代码。代码要长得多。它真的值得吗?
class AGraphics;
class BGraphics;
class A
{
public:
// Native responsibility.
virtual void F();
// Create AGraphics for showing with graphics.
virtual AGraphics* CreateGraphics(); // ShowGraphics() becomes
// CreateGraphics().Show().
// For IO and showing table
// do similarly.
// Is this design okay???
virtual ATable* CreateTable();
virtual AIo* CreateIo();
};
// for the above code, does a follow singe responsibility principle?
class B : public A
{
public:
// Native responsibility.
virtual void F();
// Create AGraphics for showing with graphics.
virtual BGraphics* CreateGraphics();
virtual BTable* CreateTable();
virtual BIo* CreateIo();
private:
// Include attributes required for native responsibility.
};
class AGrahics
{
public:
// Show with graphics.
virtual void ShowGraphics();
};
class BGrahics : public AGrahics
{
public:
// Show with graphics.
virtual void Show();
public:
B* b; // need B's data attributes.
// Include attributes required for showing with graphics.
};