Hatena::ブログ(Diary)

yoshiringの日記

2010年03月28日 [designPatterns] Factory Method このエントリーを含むブックマーク

UML
+-----------------+  +-----------------+
| Product         |  | Creator         |
+-----------------+  +-----------------+
| eat()           |  | factoryMethod() |
+-----------------+  +-----------------+
        A                     A
        |                     |
        |                     |
+-----------------+  +-----------------+
| Food            |  | FoodCreator     |
+-----------------+  +-----------------+
| eat()           |  | factoryMethod() |
+-----------------+  +-----------------+
        ^                     |
        |                     |
        +---------------------+

Python
class Product:
	def eat(self):
		pass

class Creator(object):
	def factoryMethod(self, owner):
		pass

class Food(Product):
	def __init__(self, owner):
		self.owner = owner
		print "cook %s" %(self.owner)
	def eat(self):
		print "eat %s" %(self.owner)

class FoodCreator(Creator):
	def factoryMethod(self, owner):
		return Food(owner)

creator = FoodCreator()
food1 = creator.factoryMethod("Kappa Maki")
food2 = creator.factoryMethod("Chocolate Cake")
food1.eat()
food2.eat()
C#
using System;

namespace FactoryMethod
{
    public abstract class Product
    {
        public abstract void Eat();
    }

    public abstract class Creator
    {
        public abstract Food FactoryMethod(string foodName);
    }

    public class Food : Product
    {
        private string foodName;

        public Food(string foodName)
        {
            this.foodName = foodName;
            Console.WriteLine(string.Format("cook {0}", foodName));
        }

        public override void Eat()
        {
            Console.WriteLine(string.Format("eat {0}", foodName));
        }
    }

    public class FoodCreator : Creator
    {
        public override Food FactoryMethod(string foodName)
        {
            return new Food(foodName);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Creator creator = new FoodCreator();
            Food food1 = creator.FactoryMethod("Kappa Maki");
            Food food2 = creator.FactoryMethod("Chocolate Cake");
            food1.Eat();
            food2.Eat();
            Console.ReadLine();
        }
    }
}
Console
$ python FactoryMethod.py
cook Kappa Maki
cook Chocholate Cake
eat Kappa Maki
eat Chocolate Cake
References
  1. tachikawa844の日記 http://d.hatena.ne.jp/tachikawa844/20081224/1230095888
  2. Rarestyle http://www.rarestyle.net/main/patterns/patterns.aspx
  3. Wikipedia http://ja.wikipedia.org/wiki/デザインパターン_(ソフトウェア)
  4. Uml Ascii Art http://www.c2.com/cgi/wiki?UmlAsciiArt