zoukankan      html  css  js  c++  java
  • C# 一个简单的 工厂模式 例子

    首先定义一个接口类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace MY_Factory
    {
        /// <summary>
        /// interface 是接口,实现接口
        /// </summary>
        public interface ICoat
        {
            /// <summary>
            /// 方法1
            /// </summary>
            void GetYourCoat();
            /// <summary>
            /// 方法2
            /// </summary>
            void GetYourCoat2();
        }
    }

    再定义两个类,来继承此接口

    namespace MY_Factory.SimpleFactory
    {
        public class FashionCoat : ICoat
        {
            public void GetYourCoat()
            {
                Console.WriteLine("时尚上衣");//get();
            }
            public void GetYourCoat2()
            {
                Console.WriteLine("时尚上衣2");
            }
    namespace MY_Factory.SimpleFactory
    {
        public class BusinessCoat : ICoat
        {
           
            public void GetYourCoat()
            {
                Console.WriteLine("商务上衣");
                //get();
            }
            public void GetYourCoat2()
            {
                Console.WriteLine("商务上衣2");
            }

    再定义一个工厂类

    namespace MY_Factory
    {
        public class mySimpleFactory
        {
            public ICoat CreateCoat(string classname)
            {
                switch (classname.Trim().ToLower())
                {
                    case"business":
                        {
                            return new BusinessCoat();
                        }
                    case "fashion":
                        {
                            return new FashionCoat(); 
                        }
                        default :  throw new Exception("还没有你要的那种衣服");
    
               }
            }
        }
    }

    最后,调用

                ICoat Icoat;
                try
                {
                    mySimpleFactory mysf = new mySimpleFactory();
                    Console.WriteLine("我要的是时尚上衣	");
                    Icoat = mysf.CreateCoat("fashion");
                    Icoat.GetYourCoat();
    
                    Console.WriteLine("我还要一件商务上衣	");
                    Icoat = mysf.CreateCoat("business");
                    Icoat.GetYourCoat();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
  • 相关阅读:
    java jmap,jstat等工具的使用
    jvm 参数配置
    python NameError: name 'false' is not defined
    aiflow Global variable explicit_defaults_for_timestamp needs to be on (1) for mysql
    TX 笔试题总结
    POJ 3140 Contestants Division
    POJ 1018 Communication System
    POJ 3260 The Fewest Coin
    Leetcode: Median of two sorted Array
    基础知识 (二)
  • 原文地址:https://www.cnblogs.com/jcdd-4041/p/3443239.html
Copyright © 2011-2022 走看看