zoukankan      html  css  js  c++  java
  • C# 设计模式工厂模式(Factory)

    1、工厂模式

    factory从若干个可能类创建对象。

    例如:如果创建一个通信类接口,并有多种实现方式,可以使用factory创建一个实现该接口的对象,factory可以根据我们的选择,来创建适合的对象。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Timers;
    
    namespace Demo
    {
        
        public interface ICommunication
        {
            bool Send(object data);
        }
    
        public class Serial:ICommunication
        {
            public bool Send(object data)
            {
                Console.WriteLine("通过串口发送一个数据");
                return true;
            }
        }
    
        public class Lan:ICommunication
        {
            public bool Send(object data)
            {
                Console.WriteLine("通过网口发送一个数据");
                return true;
            }
        }
    
        public class CommunicationFactory
        {
            public ICommunication CreateCommunicationFactory(string style)
            {
                switch(style)
                {
                    case "Serial":
                        return new Serial();
                    case "Lan":
                        return new Lan();
                }
                return null;
            }
        }
    
        class Program
        {  
            static void Main(string[] args)
            {
                CommunicationFactory factory = new CommunicationFactory();
                Console.WriteLine("请输入通信类型:Lan、Serial");
                string input = Console.ReadLine();
                object data = new object();
                factory.CreateCommunicationFactory(input).Send(data);
                Console.ReadKey();  
            }
        }
    }

    运行结果:

    截图20160127101926005

  • 相关阅读:
    多色图标字体
    css编写规则BEM
    css处理工具PostCss
    vue2.0点击其他任何地方隐藏dom
    vue2.0多页面开发
    Dijkstra算法(邻接矩阵存储)
    kmp算法c++代码实现
    最小生成树(prim算法,Kruskal算法)c++实现
    字符串匹配的KMP算法(转)
    筛选法求素数
  • 原文地址:https://www.cnblogs.com/sunqiliang/p/5162823.html
Copyright © 2011-2022 走看看