使用标记类,控制逻辑流程 [英] Using marker classes to control logic flow

查看:119
本文介绍了使用标记类,控制逻辑流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在经历一些code看出,我的一个同事正在使用标志类来控制程序逻辑(见下面的人为的例子)。它似乎运作良好,而code读取真的很好,但只是一些关于它的气味......

I have been going through some code seen that a colleague of mine is using 'marker classes' to control program logic (see contrived example below). It seems to work well, and the code reads really nicely, but there is just something about it that smells...

namespace ConsoleApplication4983
{
    public class MyClass
    {
        static void Main()
        {
            var c = new MyClass();
            c.DoSomething(new Sequential());
            c.DoSomething(new Random());
        }

        public void DoSomething(ProcessingMethod method)
        {
            if (method is Sequential)
            {
                // do something sequential
            }
            else if (method is Random)
            {
                // do something random
            }
        }
    }

    public class ProcessingMethod {}
    public class Sequential : ProcessingMethod {}
    public class Random : ProcessingMethod {}
}

什么是达到同样的效果更好的办法?枚举?属性?

What would be a better way of achieving the same effect? Enums? Attributes?

推荐答案

标记的接口是一个更好的做法,为他们提供了更多的灵活性。

Marker interfaces are a better practice as they offer much more flexibility.

然而,在这种特殊情况下,我认为虚拟调度是一个较好的解决方案。

However in this specific case I think that virtual dispatch is a better solution.

using System;

namespace ConsoleApplication4983
{
    public class MyClass
    {
    	static void Main()
    	{
    		var c = new MyClass();
    		c.DoSomething(new Sequential());
    		c.DoSomething(new Random());
    	}

    	public void DoSomething(ProcessingMethod method)
    	{
    		method.Foo();
    	}
    }

    public class ProcessingMethod
    {
    	public virtual void Foo() { }
    }
    public class Sequential : ProcessingMethod
    {
    	public override void Foo() { }
    }
    public class Random : ProcessingMethod
    {
    	public override void Foo() { }
    }
}

这篇关于使用标记类,控制逻辑流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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