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);
                }
  • 相关阅读:
    1. jQuery中的DOM操作
    jQuery查找节点(选择器)
    机器学习基础
    CRF
    NP
    LP
    kernel
    SVM
    凸优化和对偶
    语音识别 -- 概述
  • 原文地址:https://www.cnblogs.com/jcdd-4041/p/3443239.html
Copyright © 2011-2022 走看看