加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

工厂方法实现 – C.

发布时间:2020-12-16 10:55:16 所属栏目:百科 来源:网络整理
导读:我有“工厂”设计模式实现的以下代码. class Pen{public: virtual void Draw() = 0;};class RedPen : public Pen{public: virtual void Draw(){ cout "Drawing with red pen" endl; }};class BluePen : public Pen{public: virtual void Draw(){ cout "Drawi
我有“工厂”设计模式实现的以下代码.

class Pen{
public:
     virtual void Draw() = 0;
};

class RedPen : public Pen{
public:
     virtual void Draw(){
         cout << "Drawing with red pen" << endl;
     }
};

class BluePen : public Pen{
public:
     virtual void Draw(){
         cout << "Drawing with blue pen" << endl;
     }
};

auto_ptr<Pen> createPen(const std::string color){
     if(color == "red")
         return auto_ptr<Pen>(new RedPen);
     else if(color == "blue")
         return auto_ptr<Pen>(new BluePen);
}

但我听说可以使用“C模板”以更好的方式完成.任何人都可以帮助它如何完成以及模板方法如何比这更好?

有什么想法吗

解决方法

在您发布的示例中,工厂或模板方法对我来说都没有意义.
我的解决方案涉及Pen类中的数据成员.

class Pen {
public:
    Pen() : m_color(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_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,green());
        os << buf;

        sprintf(buf,blue());
        os << buf;

        sprintf(buf,alpha());
        os << buf;

        return os.str();
    }

private:
    int m_red;
    int m_green;
    int m_blue;
    int m_alpha;
}

当然,颜色类必须根据您使用的绘图API进行调整 – 也许比这个更先进(不同的颜色空间等).

为什么不模板?

使用模板没有意义的原因是(推测)不同绘图操作之间的唯一区别是颜色变量.因此,通过使用模板(或手动声明不同的类,就像您所做的那样),您将复制类似的代码.这将使您的程序变大,并减慢它.

因此,绘制函数应该将颜色作为参数,或者(如我的示例中)将颜色作为类数据成员.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读