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();
    }
    }
    }
  • 相关阅读:
    简单地通过Python库使用python的socket编程
    js 实现继承的几种方式
    JAVA中获取当前系统时间
    IntelliJ Idea 常用快捷键列表
    关于报错:There is already 'xxxController' bean method的解决方法
    mysql 使用 GROUP BY 时报错 ERROR 1055 (42000)
    安装系统,用cmd进行分区
    Bootstrap关闭当前页
    bootstrap的日期选择器
    Bootstrap如何关闭弹窗
  • 原文地址:https://www.cnblogs.com/HondaHsu/p/732079.html
Copyright © 2011-2022 走看看