天天看點

C#簡單工廠和抽象類的執行個體

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 模拟磁盤打開檔案
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("請選擇要進入的磁盤");
            string path = Console.ReadLine();
            Console.WriteLine("請選擇要打開的檔案");
            string fileName = Console.ReadLine();
            FileFarher ff = GetFile(fileName,path+fileName);//傳回的是被之類重寫的FileFarher 
                ff.OpenFile();
            Console.ReadLine();
        }
        public static FileFarher GetFile(string filename,string fullpath)
        {
            string extension = Path.GetExtension(filename);
            FileFarher ff = null;
            switch (extension)
            {
                case ".txt":ff = new TxTPath(fullpath);
                    break;
                case ".jpg":ff = new JpgPath(fullpath);
                    break;
            }
            return ff;
        }
    }
    public abstract class FileFarher   //父類
    {
        public string fileName
        {
            get;
            set;
        }
        public FileFarher(string filename)
        {
            this.fileName = filename;
        }
    public abstract void OpenFile();
    }
    public class TxTPath : FileFarher  //繼承父類
    {    public TxTPath(string filename) : base(filename)   //繼承父類中的filename
        {

        }
        public override void OpenFile()
        {
            ProcessStartInfo pso = new ProcessStartInfo(this.fileName);
            Process p = new Process();
            p.StartInfo = pso;
            p.Start();
        }
    }
    public class JpgPath : FileFarher   //繼承父類
    {
        public JpgPath(string filename) : base(filename) //繼承父類中的filename
        {

        }
        public override void OpenFile()
        {
            
        }
    }
}