简单工厂模式

using System;
using System.Collections.Generic;
using System.Text;

namespace Win.DesignPatterns.SimpleFactory
{
    
public interface Fruit
    {
        
//生长
        void grow();
        
//收获
        void harvest();
        
//种植
        void plant();
    }

    
public class Apple : Fruit
    {
        
public Apple()
        {
        }

        
public void grow()
        {
            Console.WriteLine(
"Apple is growing.");
        }

        
public void harvest()
        {
            Console.WriteLine(
"Apple is harvesting.");
        }

        
public void plant()
        {
            Console.WriteLine(
"Apple is planting.");
        }
    }

    
public class Strawberry : Fruit
    {
        
public Strawberry()
        {
        }

        
public void grow()
        {
            Console.WriteLine(
"Strawberry is growing.");
        }

        
public void harvest()
        {
            Console.WriteLine(
"Strawberry is harvesting.");
        }

        
public void plant()
        {
            Console.WriteLine(
"Strawberry is planting.");
        }
    }

    
public class FruitGardener
    {
        
//静态工厂方法
        public static Fruit factory(string which)
        {
            
if (which.Equals("Apple"))
            {
                
return new Apple();
            }
            
else if (which.Equals("Strawberry"))
            {
                
return new Strawberry();
            }
            
else
            {
                
return null;
            }
        }
    }

    
public class SimpleFactory
    {
        [STAThread]
        
static void Main(string[] args)
        {
            Fruit aFruit 
= FruitGardener.factory("Apple");//creat apple
            aFruit.grow();
            aFruit.harvest();
            aFruit.plant();
            aFruit 
= FruitGardener.factory("Strawberry");//creat strawberry
            aFruit.grow();
            aFruit.harvest();
            aFruit.plant();

            Console.ReadLine();
        }
    }
}
posted @ 2008-06-13 16:34  angushine  阅读(135)  评论(0编辑  收藏  举报