工厂方法模式+XML+反射

目录

一、工厂方法模式

二、工厂方法模式角色

三、代码实例一

四、代码实例二

五、代码实例三

六、UML图


一、工厂方法模式

工厂方法模式是工厂模式的推广,它依然使用多态性质。

本质是延迟到子类实现功能。

与抽象工厂不同的是,抽象工厂里有一族产品,如果产品家族中只有一种产品,那么抽象工厂模式就退化成了工厂方法模式。

二、工厂方法模式角色

抽象工厂接口:下面的创建对象的工厂必须实现这个接口。

具体工厂类:类似于工厂模式中的工厂类,进行创建对象。

抽象产品类:具体产品类的抽象,就如下面例子中的Operation类。

具体产品类:具体产品由具体工厂创建。

三、代码实例一

延伸工厂模式的加减乘除运算器。

第一个类接口:IFactory

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

namespace 工厂方法模式
{
    interface IFactory
    {
        Operation CreateOperation();
    }
}

然后是抽象产品类:Operation

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

namespace 工厂方法模式
{
    abstract class Operation
    {
        private double numA;
        private double numB;
        public double NumA//C#中对私有变量的访问方式
        {
            get { return numA; }
            set { numA = value; }
        }
        public double NumB
        {
            get { return numB; }
            set { numB = value; }
        }
        public virtual double getResult()
        {
            return 0;
        }
    }
}

然后是两个具体产品类:

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

namespace 工厂方法模式
{
    class OperationAdd : Operation
    {
        public override double getResult()
        {
            return NumA + NumB;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 工厂方法模式
{
    class OperationDivide : Operation
    {
        public override double getResult()
        {
            double result = 0;
            try
            {
                result= NumA / NumB;
            }catch(Exception e)
            {
                Console.WriteLine("除数不能为0");
            }
            return result;
        }
    }
}

然后是创建具体产品类的具体工厂:

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

namespace 工厂方法模式
{
    class AddFactory : IFactory
    {
        public Operation CreateOperation()
        {
            return new OperationAdd();
            //返回一个对象
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 工厂方法模式
{
    class DivFactory : IFactory
    {
        public Operation CreateOperation()
        {
            return new OperationDivide();
        }
    }
}

然后是一个测试类:

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

namespace 工厂方法模式
{
    class Program
    {
        static void Main(string[] args)
        {
            IFactory operFactory = new DivFactory();
            Operation ope = operFactory.CreateOperation();
            ope.NumA = 124;
            ope.NumB = 6;
            Console.WriteLine(ope.getResult());
        }
    }
}

XML+反射更改此模式

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FactoryMethod
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
             string AssemblyName = "FactoryMethod";
             string db = ConfigurationManager.AppSettings["Operation"];
            string className = AssemblyName + "." + "Factory"+db;
            Console.WriteLine(className);
            IFactory USE= (IFactory)Assembly.Load(AssemblyName).CreateInstance(className);
            Operation ope = USE.CreateOperation();
            ope.NumA = 1;
            ope.NumB = 9;
            Console.WriteLine(ope.getResult());
             
    }
    }
}

 

四、代码实例二

类似于上文的运算器,这个代码实例是关于灯的开关。

第一个是接口类IFactory,下面的具体工厂类都要实现它

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

namespace 工厂方法模式一
{
    interface IFactory
    {
         Light CreateFactory();
    }
}

:第二个类是抽象灯类:

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

namespace 工厂方法模式一
{
    abstract class Light
    {
        public abstract void TurnOn();
        public abstract void TurnOff();
    }
}

然后是具体灯类:

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

namespace 工厂方法模式一
{
    class TubeLight : Light
    {
        public override void TurnOff()
        {
            Console.WriteLine("TubeLight off");
        }

        public override void TurnOn()
        {
            Console.WriteLine("TubeLight on");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 工厂方法模式一
{
    class BulbLight : Light
    {
        public override void TurnOff()
        {
            Console.WriteLine("BulbLight off");
        }

        public override void TurnOn()
        {
            Console.WriteLine("BulbLight on");
        }
    }
}

接着是具体工厂类:

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

namespace 工厂方法模式一
{
    class BulbFactory : IFactory
    {
        public Light CreateFactory()
        {
            return new BulbLight();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 工厂方法模式一
{
    class TubeFactory : IFactory
    {
        public Light CreateFactory()
        {
            return new TubeLight();
        }
    }
}

测试类:

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

namespace 工厂方法模式一
{
    class Program
    {
        static void Main(string[] args)
        {
            IFactory Light1 = new BulbFactory();
            Light li = Light1.CreateFactory();
            li.TurnOn();
            li.TurnOff();
            Console.WriteLine("-----------");
            IFactory light2 = new TubeFactory();
            Light le = light2.CreateFactory();
            le.TurnOn();
            le.TurnOff();
            //
        }
    }
}

五、代码实例三

数据的导入,还没学会c#数据库具体使用...先用JAVA写一下。

package 工厂方法模式;

import java.io.IOException;

public interface ExportFileApi {
	public boolean export(String str) throws IOException;

}
package 工厂方法模式;

import java.io.IOException;

public abstract class ExportOperate {
	public boolean export(String str) throws IOException
	{
		ExportFileApi api=FactoryMethod();
		return api.export(str);
	}
	protected abstract ExportFileApi FactoryMethod();

}

仔细体会一下这个。 

package 工厂方法模式;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ExportDb implements ExportFileApi {

	@Override
	public boolean export(String str) {
		// TODO Auto-generated method stub
		System.out.println("现在导出数据到数据库中-------");
		Connection conn;
		PreparedStatement stmt;
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/student?useSSL=true";
		String user = "root";
		String password = "sannian1";
		String sql = "insert into scsc values (?)";

		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
			stmt = (PreparedStatement) conn.prepareStatement(sql);
			stmt.setString(1, str);
			stmt.executeUpdate();//
			stmt.close();
			conn.close();

		} catch (ClassNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return true;
	}

}

 

package 工厂方法模式;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class ExportFile implements ExportFileApi {

	@Override
	public boolean export(String str) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("现在导出数据到文件中---");
		File file1 = new File("D:/My");
		if (!file1.exists()) {
			file1.mkdirs();
		}
		/*File fs = new File("D:/My/in1.txt");
		if (!fs.exists()) {
			fs.createNewFile();
		}*/
		File fw = new File("D:/My/FileOut.txt");
		if (!fw.exists()) {
			fw.createNewFile();
		}
		// 建立文件完毕;
		//Scanner cin = new Scanner(fs);// 读文件
		PrintWriter cout = new PrintWriter(fw);// 写文件
		cout.println(str);
		cout.close();
		return true;
	}

}

具体工厂类:

package 工厂方法模式;

public class ExportDbOperate extends ExportOperate {

	@Override
	protected ExportFileApi FactoryMethod() {
		// TODO Auto-generated method stub
		return new ExportDb();
	}

}
package 工厂方法模式;

public class ExportTxtOperate extends ExportOperate {

	@Override
	protected ExportFileApi FactoryMethod() {
		// TODO Auto-generated method stub
		return new ExportFile();
	}

}

然后是测试类

package 工厂方法模式;

import java.io.IOException;

public class Client {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		ExportOperate Op=new ExportDbOperate();
		Op.export("343543253");
		Op=new ExportTxtOperate();
		Op.export("dsds");
	}

}

六、UML图

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值