架构师训练营 week3 作业
作业1
作业2
实现1 通过对象组合 C++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Component {
public:
Component(string n, string t):m_name(n),m_text(t){}
void Print() const {
cout << "print " << m_name << "(" << m_text << ")" << endl;
for (auto itr = m_subs.begin(); itr != m_subs.end(); ++itr) {
(*itr)->Print();
}
}
void Add(Component& w){ m_subs.push_back(&w); }
private:
string m_name;
string m_text;
vector<Component*> m_subs;
};
int main(int argc, char const *argv[]) {
Component winform("WinForm","窗口");
Component picture("Picture","LOGO图片");
Component button1("Button","登录");
Component button2("Button","注册");
Component frame("Fram","FRAME1");
Component lable1("Lable","用户名");
Component tb1("TextBox","文本框");
Component lable2("Lable","密码");
Component pb("PasswordBox","密码框");
Component cb("CheckBox","复选框");
Component tb2("TextBox","记住用户名");
Component lb("LinkLable","忘记密码");
winform.Add(picture);
winform.Add(button1);
winform.Add(button2);
winform.Add(frame);
frame.Add(lable1);
frame.Add(tb1);
frame.Add(lable2);
frame.Add(pb);
frame.Add(cb);
frame.Add(tb2);
frame.Add(lb);
winform.Print();
return 0;
}
实现2 组合模式
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Printable {
public:
virtual void Print() = 0;
};
class Atom : public Printable
{
public:
Atom(string n, string t):m_name(n),m_text(t){}
void Print() {
cout << "print " << m_name << "(" << m_text << ")" << endl;
}
private:
string m_name;
string m_text;
};
class Container : public Printable
{
public:
Container(string n, string t):m_name(n),m_text(t){}
void Print() {
cout << "print " << m_name << "(" << m_text << ")" << endl;
for (auto itr = m_subs.begin(); itr != m_subs.end(); ++itr) {
(*itr)->Print();
}
}
void Add(Printable& w){ m_subs.push_back(&w); }
private:
vector<Printable*> m_subs;
string m_name;
string m_text;
};
int main(int argc, char const *argv[]) {
Container winform("WinForm","窗口");
Atom picture("Picture","LOGO图片");
Atom button1("Button","登录");
Atom button2("Button","注册");
Container frame("Fram","FRAME1");
Atom lable1("Lable","用户名");
Atom tb1("TextBox","文本框");
Atom lable2("Lable","密码");
Atom pb("PasswordBox","密码框");
Atom cb("CheckBox","复选框");
Atom tb2("TextBox","记住用户名");
Atom lb("LinkLable","忘记密码");
winform.Add(picture);
winform.Add(button1);
winform.Add(button2);
winform.Add(frame);
frame.Add(lable1);
frame.Add(tb1);
frame.Add(lable2);
frame.Add(pb);
frame.Add(cb);
frame.Add(tb2);
frame.Add(lb);
winform.Print();
return 0;
}
评论