あなたが投稿した例では、ファクトリまたはテンプレートのアプローチは私には意味がありません。私のソリューションには、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 に合わせて調整する必要があります。おそらく、これよりもはるかに高度なものにする必要があります (異なるカラー スペースなど)。
なぜテンプレートではないのですか?
テンプレートを使用する意味がない理由は、(おそらく) 異なる描画操作の違いは色変数だけだからです。したがって、テンプレートを使用する (または手動で別のクラスを宣言する) と、同様のコードが複製されます。これにより、プログラムが大きくなり、速度が低下します。
したがって、描画関数は色を引数として受け取るか、(私の例のように) 色をクラス データ メンバーとして持つ必要があります。