如何强制客户端设置某些属性 [英] How to force a client to set certain properties

查看:116
本文介绍了如何强制客户端设置某些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类有可以使用类之前必须设置Ten属性。

My class has ten properties that must be set before the class can be used.

我要强制(或至少非常强烈建议,最好用警告)我类的用户调用类的任何方法之前设置这些属性。

I want to force (or at least very strongly encourage, preferably with warnings) a user of my class to set these properties before calling any methods of the class.

我可以用一个构造函数值的所有属性,参数,但我不。不想,因为很多参数是笨重

I could use a constructor that takes values for all the properties as parameters but I don't want to because that many parameters would be unwieldy.

我可以检查的属性值类的所有方法里面,但这太晚了 - 我想编译时检查。

I could check the values of the properties inside all the methods of the class but this is too late - I want a compile-time check.

我该怎么办?

推荐答案

也许你可以使用 Builder模式用流利的接口的一些变化。你可以有样的,你不能跳过某些属性的步骤或什么的。例如设置您需要通过设置属性X中的方法返回的对象建设者财产年。

Maybe you can use some variation of the Builder Pattern with fluent interface. You could have kind of steps or something where you can't skip some of the properties. For example to set property Y of the builder you will need the object returned by the method that sets property X.

new Builder().SetX(10).SetY(20) //compiles because SetX returns a class with SetY method
new Builder().SetY(20) //does not compile because the builder only has SetX method

要避免多个类,你可能有多个接口一个类每个公开只有一种方法。

To avoid having multiple classes you may have one class with multiple interfaces each of which exposes only one method.

在另一方面,我可能会去的构造即使有很多参数

On the other hand I would probably go for the constructor even with a lot of parameters

这篇关于如何强制客户端设置某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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