对象转换模式 [英] Object Conversion Pattern

查看:74
本文介绍了对象转换模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有来自外部来源(不可修改)的几个不同的类代表相同的概念。例如Address。我有com.namespace1.Address(包含字段houseNum,街道,城市),com.namespace2.Address(带有字段h,s,c),namespace3.com.CoolAddress(字段house_num,street,city)。问题是我使用某些Web服务需要某些Address对象类型,因此我需要创建一个名为namespace3.com.CoolAddress的com.namespace1.Address。字段很容易映射,但我正在寻找一个如何做的模式。



从我的角度来看,一个实例对象AddressConverter不会感觉是因为没有状态(只有行为),当类只有行为时,它归结为一个实用程序类中的静态方法。从长远来看,任何时候我需要将对象映射到对方,我有一个地方可以添加/修改/删除方法。如何做到这一点可能会改变,但是我知道代码在哪里(一次),并且可以在需要时更改映射。



想法?

解决方案

我想你正在寻找的是一个工厂类。当您需要能够实例化几个相关课程之一时,使用工厂模式,由工厂决定,而不是开发人员。



请参阅 http://en.wikipedia.org/wiki/Factory_method_pattern



你是正确的尝试将所有这些业务逻辑保留在一个地方,而不是做ClassOne.toClassTwo(),ClassOne.toClassThree(),...



我可以想到实现这个(但不是最简单)的最灵活的方式是让工厂从一个简单的类开始,只有基本的常用方法,并在Hashtable或其他容器中添加处理程序。这样你就不需要具体实现每个可能的功能组合。



当然,为每一个可能的地址变体都有一个具体的实现会更快,但是将是相当数量的重复代码,并且添加新的地址类类型将会更困难。


So I have several different classes coming from external sources (unmodifiable) that represent the same concept. For example, Address. I have com.namespace1.Address (with fields houseNum, street, city), com.namespace2.Address (with fields h, s, c), namespace3.com.CoolAddress (with fields house_num, street, citY). The problem is that certain web services I use require certain Address object types so I am required to create a com.namespace1.Address given a namespace3.com.CoolAddress. The fields are easy enough to map but I'm looking for a pattern on how to do it.

From my point of view, an instance object AddressConverter doesn't make sense as there is no state (only behaviour) and when classes only have behaviour it boils down to static methods in a utility class. In the long term, anytime I need to map new objects to one another, I have one place to add/modify/remove methods. How it's done might change, but I know where the code sits (in once place) and can change the mapping when I need to.

Thoughts?

解决方案

I think what you're looking for is a factory class. The factory pattern is used when you need to be able to instantiate one of several related classes, to be determined by the factory, not the developer.

See http://en.wikipedia.org/wiki/Factory_method_pattern

You're right to try to keep all this business logic in one place instead of doing ClassOne.toClassTwo(), ClassOne.toClassThree(),...

The most flexible way I can think of implementing this (but not the easiest by far) would be to have the factory start with a simple class with only basic common methods in it, and add handlers to a Hashtable or other container. That way you don't need concrete implementations of every possible combinations of features.

Of course it would be quicker to have a concrete implementation for each possible address variant, but there would be a fair amount of duplicated code, and it would be a little harder to add new address class types.

这篇关于对象转换模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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