zoukankan      html  css  js  c++  java
  • 简单工厂

    using System;


    namespace SimpleFactoryPattern
    {
    /// <summary>
    /// 简单工厂模式示例
    /// </summary>
    class SimpleFactoryPattern
    {
    //定义Food接口
    public interface Food
    {
    //烹饪
    void Cook();
    //卖出
    void Sell();

    }

    //Noodle

    public class Noodle:Food
    {
    public Noodle()
    {
    Console.WriteLine("\nThe Noodle is made..");
    }
    private int price;

    //面条Noodle的Cook方法接口实现
    public void Cook()
    {
    Console.WriteLine("\nNoodle is cooking...");
    }

    //面条Noodle的Sell方法接口实现
    public void Sell()
    {
    Console.WriteLine("\nNoodle has been sold...");
    }
    public int Price
    {
    get{return this.price;}
    set{price=value;}
    }
    }

    //Rice
    public class Rice:Food
    {
    public Rice()
    {
    Console.WriteLine("\nThe Rice is made ..");
    }
    private int price;
    public void Cook()
    {
    Console.WriteLine("\nRice is cooking...");
    }
    public void Sell()
    {
    Console.WriteLine("\nRice has been sold...");
    }
    public int Price
    {
    get{return this.price;}
    set{price=value;}
    }
    }



    //Bread
    public class Bread:Food
    {
    public Bread()
    {
    Console.WriteLine("\nThe Bread is made....");
    }
    private int price;
    public void Cook()
    {
    Console.WriteLine("\nBread is cooking...");
    }
    public void Sell()
    {
    Console.WriteLine("\nBread has been sold...");
    }
    public int Price
    {
    get{return this.price;}
    set{price=value;}
    }
    }


    //定义大厨,他包办这个快餐店里的所有Food,包括面条,面包和米饭
    class Chef
    {
    public static Food MakeFood(string foodName)
    {
    try
    {
    switch(foodName)
    {
    case "noodle": return new Noodle();
    case "rice":return new Rice();
    case "bread":return new Bread();
    default:throw new BadFoodException("Bad food request!");
    }
    }
    catch(BadFoodException e)
    {
    throw e;
    }
    }

    }

    //异常类,该餐馆没有的食品
    class BadFoodException: System.Exception
    {
    public BadFoodException(string strMsg)
    {
    Console.WriteLine(strMsg);
    }
    }


    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
    Food food=Chef.MakeFood("bread");
    food.Cook();
    food.Sell();
    Console.ReadLine();
    }
    }
    }
  • 相关阅读:
    XCode4 App Store提交小结
    Android Fragment完全解析,关于碎片你所需知道的一切
    [iOS开发系列]根据Debug和Release状态的变化来屏蔽日志输出
    iOS5可能会删除本地文件储存
    iOS5可能会删除本地文件储存
    应用中弹出 WiFi 提示框的方法
    cannot be translated into a null value due to being declared as a primitive type. Consid
    在pom.xml文件中自定义JDK版本+阿里maven镜像修改
    Docker化tomcat 并且使用maven热部署
    使用wget下载JDK8
  • 原文地址:https://www.cnblogs.com/HondaHsu/p/732079.html
Copyright © 2011-2022 走看看