首页 > 代码库 > C#简单工厂模式(文件案例)

C#简单工厂模式(文件案例)

wKioL1NiFJqhEwZFAAGKq5llVuA835.jpg

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 读文件案例
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入文件名");
            string fileName = Console.ReadLine();//获得用户输入
            File file = Factory.GetFileName(fileName);
            file.OpenFile();
            Console.ReadKey();
        }
    }
    /// <summary>
    /// 父类,等待子类实现
    /// </summary>
    public abstract class File
    {
        private string _fileName;//文件名
        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }
        private string _extension;//后缀名
        public string Extension
        {
            get { return _extension; }
            set { _extension = value; }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="fileName"></param>
        public File(string fileName)
        {
            //在本类中,用私有字段即可,不必要使用属性来保护对应的字段
            this._fileName = Path.GetFileNameWithoutExtension(fileName);
            this._extension = Path.GetExtension(fileName);
        }
        public abstract void OpenFile();
    }
    public class TxtFile : File
    {
        /// <summary>
        /// 子类构造函数,调用父类构造函数为字段赋值
        /// </summary>
        /// <param name="fileName"></param>
        public TxtFile(string fileName)
            : base(fileName)
        { }
        public override void OpenFile()
        {
            //此时就需要用属性来保护字段了
            Console.WriteLine("文件名为{0},后缀名为{1}", this.FileName, this.Extension);
        }
    }
    public class AviFile : File
    {
        public AviFile(string fileName)
            : base(fileName)
        { }
        public override void OpenFile()
        {
            Console.WriteLine("文件名为{0},后缀名为{1}", this.FileName, this.Extension);
        }
    }
    public class Factory
    {
        public static File GetFileName(string fileName)
        {
            File file = null;
            switch (Path.GetExtension(fileName).ToLower())
            {
                case "txt":
                case ".txt": file = new TxtFile(fileName); break;
                case "avi":
                case ".avi": file = new AviFile(fileName); break;
                //父类是虚方法的写法
                //case "txt":
                //case ".txt": return new TxtFile(fileName);
                //default: return new File(fileName);
            }
            return file;
        }
    }
}


本文出自 “三人行,必有我师焉。” 博客,请务必保留此出处http://hexdong.blog.51cto.com/3720427/1405351