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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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;
        }
    }
}