简体   繁体   English

简单的代码设计问题

[英]Simple code design question

I have a 3 layer app. 我有一个3层应用程序。 The second layer is receiving and object from the 3rd layer and there are two attributes from this object that I need to pass on to the 1st layer (UI). 第二层是第三层的接收对象,第二层是我需要传递给第一层(UI)的两个属性。 Should I make this object's class visible in the 1st layer (by importing it's package/namespace, which I'm trying to avoid) or should I pass on these attributes as an string array (I'd rather have an Object array, but they're a string and an int types in Java 1.4) and cast them to their proper types in compilation time (Their types are fixed, so thankfully this is an option)? 我应该在第1层中使该对象的类可见(通过导入它的包/名称空间,我试图避免这种情况),还是应该将这些属性作为字符串数组传递(我宁愿有一个Object数组,但它们是Java 1.4中的字符串和int类型),并在编译时将其转换为正确的类型(它们的类型是固定的,所以谢天谢地,这是一个选择)?

That's what DTOs (Data Transfer Objects) are for. 这就是DTO(数据传输对象)的用途。 So in short: use Objects in your top-level interface. 简而言之:在顶级界面中使用对象。

I'm no java expert, but I can offer some general advice from a .NET perspective. 我不是Java专家,但是我可以从.NET角度提供一些一般性建议。 Since that's your background it should be relevant to you. 由于这是您的背景,因此应该与您相关。

Should I make this object's class visible in the 1st layer (by importing it's package/namespace, which I'm trying to avoid 我是否应该在第1层中使该对象的类可见(通过导入它的包/命名空间,我试图避免这种情况)

Its OK to import the namespace. 可以导入名称空间。 While it may feel like you decrease coupling, this is better than a string array as it does not require expensive boxing . 虽然感觉像减少了耦合,但这比字符串数组要好,因为它不需要昂贵的装箱

Do not forget that readability is always a serious consideration. 不要忘记可读性始终是一个认真的考虑。 I recommend you take a look at the MVC pattern. 我建议您看一下MVC模式。

Sounds like JavaBeans are your friend, although you'll probably not profit from reusability/serializabiliy. 听起来JavaBeans是您的朋友,尽管您可能不会从可重用性/可序列化中受益。

JavaBeans are classic DTOs ( Data Transfer Objects ), used to pass along information in your program. JavaBean是经典的DTO( 数据传输对象 ),用于传递程序中的信息。

What kind of UI do you have? 您拥有哪种UI? Swing? 摇摆? Then DTOs is probably the way to go. 然后,DTO可能就是要走的路。 Consider to put the DTO classes in a project of its own, which then can be shared by the client side and the server side. 考虑将DTO类放在自己的项目中,然后可以由客户端和服务器端共享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM