文章出處
文章列表
索引
將對一個類的所有對象的管理封裝到一個單獨的管理器類中。
這使得管理職責的變化獨立于類本身,并且管理器還可以為不同的類進行重用。
Encapsulates management of a class’s objects into a separate manager object.
This allows variation of management functionality independent of the class and the manager’s reuse for different classes.
Subject
- 領域對象。
- 提供 Client 需要的領域服務。
Manager
- Manager 類是唯一負責創建和銷毀 Subject 對象的類。它負責跟蹤和管理 Subject 對象。
- 典型的管理職責包括根據指定的 Key 搜索 Subject 對象。
- 因為 Subject 對 Manager 無引用,所以 Manager 可根據需要修改或子類化。
Client
- 從 Manager 對象獲取 Subject 對象。
- 使用 Subject 的領域服務。
當以下情況成立時可以使用 Manager 模式:
- 當需要對同一個類的所有的對象進行操作時。
- 當需要按需的創建和銷毀對象時。
- 當需要控制對象的生命周期時。
- 可以對全部對象進行統計。
- 管理職責可以無依賴的變化。
- 可以按需替換管理職責。
- 管理職責可以得到重用
1 namespace ManagerPattern.Implementation1 2 { 3 public class Book 4 { 5 public Book(string isbn, string authors, string title) 6 { 7 this.ISBN = isbn; 8 this.Authors = authors; 9 this.Title = title; 10 } 11 12 public string ISBN { get; private set; } 13 public string Authors { get; private set; } 14 public string Title { get; private set; } 15 16 public string Publisher { get; set; } 17 public Image Cover { get; set; } 18 19 public string GetTableOfContents() 20 { 21 return "something"; 22 } 23 } 24 25 public class BookManager 26 { 27 private Dictionary<string, Book> _books 28 = new Dictionary<string, Book>(); 29 30 public BookManager() 31 { 32 } 33 34 public Book AddBook(string isbn, string authors, string title) 35 { 36 Book book = new Book(isbn, authors, title); 37 _books.Add(book.ISBN, book); 38 return book; 39 } 40 41 public Book GetBookByISBN(string isbn) 42 { 43 Book book; 44 _books.TryGetValue(isbn, out book); 45 return book; 46 } 47 48 public IEnumerable<Book> FindBooksOfAuthor(string author) 49 { 50 return _books.Values.Where(b => b.Authors.Contains(author)); 51 } 52 } 53 54 public class Client 55 { 56 public void TestCase1() 57 { 58 BookManager manager = new BookManager(); 59 manager.AddBook("xxxx-xxxx-xxxx", "Dennis Gao", "Good Man"); 60 Book book = manager.GetBookByISBN("xxxx-xxxx-xxxx"); 61 book.GetTableOfContents(); 62 } 63 } 64 }
《設計模式之美》為 Dennis Gao 發布于博客園的系列文章,任何未經作者本人同意的人為或爬蟲轉載均為耍流氓。
文章列表
全站熱搜