Thứ Ba, 24 tháng 7, 2012

Design Pattern - Factory Method

1. Ý nghĩa
Định nghĩa 1 interface cho việc tạo đối tượng nhưng lớp con kế thừa nó quyết định đối tượng được tạo.

2. UML
  • Product  (Page)
    • defines the interface of objects the factory method creates
  • ConcreteProduct  (SkillsPage, EducationPage, ExperiencePage)
    • implements the Product interface
  • Creator  (Document)
    • declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
    • may call the factory method to create a Product object.
  • ConcreteCreator  (Report, Resume)
    • overrides the factory method to return an instance of a ConcreteProduct.
3. Code demo
    abstract class Product
    {
    }
    class ConcreteProductA: Product
    {

    }
    class ConcreteProductB : Product
    {
    }
    abstract class Creator
    {
        public abstract Product FactoryMethod();
    }

    class ConcreteCreatorA : Creator
    {
        public override Product FactoryMethod()
        {
            //throw new NotImplementedException();
            return new ConcreteProductA();

        }
    }
    class ConcreteCreatorB : Creator
    {
        public override Product FactoryMethod()
        {
            //throw new NotImplementedException();
            return new ConcreteProductB();
        }
    }

Không có nhận xét nào:

Đăng nhận xét