将标志传递给对象的正确设计模式 [英] Proper design pattern for passing flags to an object

查看:121
本文介绍了将标志传递给对象的正确设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中我做了这样的事情

In C I've done this sort of thing

enum { USE_COKE = 1,
        USE_PEPSI = 2,
        USE_JUICE = 4,
        USE_WATER = 8 };

 int makeDrink(int flags);

 //...

 int rcode = makeDrink(USE_COKE | USE_JUICE | USE_WATER);

我知道这是非常标准的,它也用于 iostream 例如。我想知道如何将这种设计模式转化为Java或OOP?我很漂亮肯定多态不是去这里的方式,因为如果(flag_is_set)块代码,我的代码会更好一些比重写大部分程序。有一个实用程序标志类,或使用配置对象或枚举执行此操作的首选方式,或一堆ints等。

I know this is pretty standard, it's also used in iostream for instance. I'm wondering how to translate this design pattern into Java or OOP? I'm pretty sure polymorphism is not the way to go here since it'd be better for my code to have an if(flag_is_set) block than rewrite much of the routine. Is there a utility Flags class, or a preferred way to do this using a configuration object, or an enum, or a bunch of ints, etc.

推荐答案

Java有枚举。以下是教程

Java has enumerations. Here's the tutorial.

我将使用这些over int等。它是一个类型安全的解决方案,由于枚举是对象,您可以附加行为,避免 switch 语句。

I would use these over ints etc. It's a type-safe solution, and since enums are objects, you can attach behaviours and avoid switch statements.

您可以使用 EnumSet 。从文档:


用于枚举类型的专门的Set实现....这个
表示是非常紧凑和高效的。这个类的空间和时间
的性能应该足够好,可以使用它作为一个
高质量的,类型安全的替代传统的基于int的bit
标志。

A specialized Set implementation for use with enum types .... This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags."

这篇关于将标志传递给对象的正确设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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