如何使可插拔的静态类 [英] How to make pluggable static classes

查看:149
本文介绍了如何使可插拔的静态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使可插拔的东西在C#。定义一个接口, Activator.CreateInstance(小于类>)等,或者我可以明确创建插入类的一个实例的code路径。方法很多。

I know how to make pluggable things in c#. Define an Interface, Activator.CreateInstance(<class>), etc. Or I can have a code path that explicitly creates an instance of the plugged class. Many ways.

但是,如果我想使可插拔的服务是静态的(我知道我可以重构,以便它不是但这不是问题的点)

But what if the service I want to make pluggable is static (I know I could refactor so that it's not but that's not the point of the question)

具体的例子。我有一个类,它提供的磁盘I / O的抽象(读取文件,列出目录,....)。现在,我想这个抽象,供应的文件,比如说,从一个真正的FS,一个数据库的不同实现。

Concrete example. I have a class that provides disk I/O abstraction (Read File, List Directory,....). Now I want different implementations of this abstraction that serves up files from , say, a real FS, a database.

根据奥利维尔Jacot-Descombes的答复,我将有一个文件系统类(即实)这样的

Based on Olivier Jacot-Descombes reply, I will have a FileSystem class (that is real) like this

public static class FileSystem
{
    static IFSImplemenation s_imple;
    static FileSystem()
    {
        if(<some system setting>)
            // converted to singleton instead of static
            s_imple = new OldFileSystem() 
        else
            s_imple = new DbFileSystem();
    }

    public static byte[] ReadFile(string path)
    {
        return s_imple.ReadFile(path);
    }

    ...
}

要重申 - 我有一个庞大的身躯code,我不想改变,因此重要的是要保持调用签名是相同的 - 该解决方案实现了。

To reiterate - I have a large body of code that I dont want to change so it was important to keep the calling signature the same - this solution achieves that

推荐答案

使用您的静态类作为门面的非静态实施

Use your static class as facade for non-static implementations

public static class DB
{
    private static IDbInterface _implementation;

    public static void SetImplementation(IDbInterface implementation)
    {
        _implementation = implementation;
    }

    public static Customer GetCustomerByID(int custId)
    {
        return _implementation.GetCustomerByID(custId);
    }

    ...
}

这篇关于如何使可插拔的静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆