在您发布的示例中,工厂或模板方法对我来说都没有意义。我的解决方案涉及 Pen 类中的数据成员。
class Pen {
public:
Pen() : m_color(0,0,0,0) /* the default colour is black */
{
}
Pen(const Color& c) : m_color(c)
{
}
Pen(const Pen& other) : m_color(other.color())
{
}
virtual void Draw()
{
cout << "Drawing with a pen of color " << m_color.hex();
}
void setColor(const Color& c) { m_color = c; }
const Color& color() const { return m_color; }
private:
Color m_color;
};
class Color {
public:
Color(int r, int g, int b, int a = 0) :
m_red(r), m_green(g), m_blue(other.blue()), m_alpha(a)
{
}
Color(const Color& other) :
m_red(other.red()), m_green(other.green()),
m_blue(other.blue()), m_alpha(other.alpha())
{
}
int red() const { return m_red; }
int green() const { return m_green; }
int blue() const { return m_blue; }
int alpha() const { return m_alpha; }
std::string hex() const
{
std::ostringstream os;
char buf[3];
os << "#";
sprintf(buf, "%2X", red());
os << buf;
sprintf(buf, "%2X", green());
os << buf;
sprintf(buf, "%2X", blue());
os << buf;
sprintf(buf, "%2X", alpha());
os << buf;
return os.str();
}
private:
int m_red;
int m_green;
int m_blue;
int m_alpha;
}
当然,颜色类必须根据您使用的绘图 API 进行调整——并且可能比这个更高级(不同的颜色空间等)。
为什么不是模板?
使用模板没有意义的原因是(可能)不同绘图操作之间的唯一区别是颜色变量。因此,通过使用模板(或像您一样手动声明不同的类),您将复制类似的代码。这将使您的程序变大,并减慢它的速度。
因此,draw 函数应该将颜色作为参数,或者(如在我的示例中)将颜色作为类数据成员。