close
This tutorial is about composite pattern, which is my thoghts after watching the tutorial created by Christopher Okhravi.
The desired ouput contents in form of html are shown below:
Create a new console project and add a interface item into it first.
TodoList portion:
1: namespace CompositePatternConsole
2: {
3: interface TodoList
4: {
5: void Add(TodoList todoList);
6: void Remove(TodoList todoList);
7: string GetHtml();
8: }
9: }
Todo portion:
1: namespace CompositePatternConsole
2: {
3: class Todo : TodoList
4: {
5: string text;
6: public Todo(string _text)
7: {
8: this.text = _text;
9: }
10:
11: public void Add(TodoList todoList)
12: {
13: Console.WriteLine("Todo(leaf) cannot add anything.");
14: //throw new NotImplementedException();
15: }
16:
17: public string GetHtml()
18: {
19: return this.text;
20: //throw new NotImplementedException();
21: }
22:
23: public void Remove(TodoList todoList)
24: {
25: Console.WriteLine("Todo(leaf) cannot be removed.");
26: }
27: }
28: }
Project portion:
1: namespace CompositePatternConsole
2: {
3: class Project : TodoList
4: {
5: string title;
6: IList<TodoList> todos =new List<TodoList>();
7: public Project(string title)
8: {
9: this.title = title;
10: }
11: public Project(IList<TodoList> _todos)
12: {
13: this.todos = _todos;
14: }
15:
16: public void Add(TodoList todoList)
17: {
18: todos.Add(todoList);
19: }
20:
21: public string GetHtml()
22: {
23: string html = "<hl>";
24: html += this.title;
25: html += "</hl><ul>";
26: foreach(TodoList tl in this.todos)
27: {
28: html += "<li>";
29: html += tl.GetHtml();
30: html += "</li>";
31: }
32: html += "</ul>";
33: return html;
34: }
35:
36: public void Remove(TodoList todoList)
37: {
38: todos.Remove(todoList);
39: }
40: }
41: }
Console portion:
The following is the architecture of above case:
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: Project four_1 = new Project("Four-1");
6: four_1.Add(new Todo("Four 1-1"));
7: four_1.Add(new Todo("Four 1-2"));
8:
9: Project four_2 = new Project("Four-2");
10: four_2.Add(new Todo("Four 2-1"));
11: four_2.Add(new Todo("Four 2-2"));
12:
13: Project four = new Project("four");
14: four.Add(four_1);
15: four.Add(four_2);
16:
17: Project three = new Project("three");
18: three.Add(four);
19:
20: Project two = new Project("two");
21: two.Add(three);
22:
23: Project project = new Project("One");
24: project.Add(two);
25:
26: string html = project.GetHtml();
27: Console.WriteLine(html);
28: Console.ReadKey();
29:
30: }
31: }
Copy the contents shown above and paste them in a html file, then you can see the results like this:
全站熱搜
留言列表