我有几个客户端代码必须执行if检查的实例,如下所示:
void Client::Method1()
{
if (flag is true)
{
m_Object.DoSomething();
}
else
{
m_Object.DoSomethingElseInstead();
}
}
void Client::Method2()
{
if (flag is true)
{
m_Object.DoSomething2();
}
else
{
m_Object.DoSomethingElseInstead2();
}
}
void Client::Method3()
{
if (flag is true)
{
m_Object.DoSomething3();
}
else
{
m_Object.DoSomethingElseInstead3();
}
}
等等......
我想封装if(标志)检查,如果可能的话,以某种方式在m_Object内部处理。我想过使用PIMPL习惯用法,但我真正需要的是以某种方式封装这种行为。有更简单的方法吗?
答案 0 :(得分:2)
您可以使用strategy pattern。类似的东西:
class Strategy
{
public:
virtual ~Strategy() = default;
virtual void Method1() = 0;
virtual void Method2() = 0;
virtual void Method3() = 0;
};
class Strategy1 : public Strategy
{
public:
explicit Strategy1(Client& client) : client(client) {}
void Method1() override {client.m_Object.DoSomething();}
void Method2() override {client.m_Object.DoSomething2();}
void Method3() override {client.m_Object.DoSomething3();}
private:
Client& client;
};
class Strategy2 : public Strategy
{
public:
explicit Strategy2(Client& client) : client(client) {}
void Method1() override {client.m_Object.DoSomethingElseInstead();}
void Method2() override {client.m_Object.DoSomethingElseInstead2();}
void Method3() override {client.m_Object.DoSomethingElseInstead3();}
private:
Client& client;
};
class Client
{
public:
Client() { SetFlag(true); }
void Method1() { strategy->Method1(); }
void Method2() { strategy->Method2(); }
void Method3() { strategy->Method3(); }
void SetFlag(bool flag) // or better: SetStrategy
{
if (flag) {
strategy = std::make_unique<Strategy1>(*this);
} else {
strategy = std::make_unique<Strategy2>(*this);
}
}
private:
std::unique_ptr<Strategy> strategy;
Object m_Object;
};
答案 1 :(得分:0)
我会这样做:
m_Object.DoSomething1(flag); // or
m_Object.DoSomething2(flag); // or
m_Object.DoSomething3(flag);
例如,DoSomething1
的实施将是:
Object::DoSomething1(bool flag)
{
if (flag)
{
// Something here.
}
else
{
// Something else here.
}
}
不会使代码更实用,但仍然非常简单易读,并且您将标志进一步检查(循环)。