2013-08-08 5 views
1

특정 플랫폼/공급 업체 API에 의존하지 않는 가벼운 클라이언트 용 API를 개발 한 웹 서비스 인터페이스의 일부입니다.유형을 A에서 B로 또는 그 반대로 변환 스칼라

이제 이러한 서비스 특성은 들어오는 데이터를 전달하는 이러한 플랫폼 불가지론 유형을 impl 메소드가 그대로 작동하도록 공급 업체 특정 유형으로 변환해야합니다. 벤더 API의 코드를 변경할 수있는 기능이 없다는 점에 유의하십시오. 우리는 이러한 유형의 변환을 양방향으로 수행 할 수있는 일종의 어댑터/변환 API를 만들어야한다고 생각합니다. 일부 공급 업체 유형은 매우 신빙성이 있습니다. 예 : 더 가벼운 웨이트 서비스 인터페이스는 모든 데이터를 전달하는 평평한 유형을 가질 수 있지만 벤더 API는 입력 데이터 등을 취할 수있는 계층 적 유형을가집니다. 반환 유형의 경우도 마찬가지입니다. 스칼라에서 이것을 달성하는 가장 좋은 방법은 무엇입니까?

편집 : 실시 예

case class A(var1,var2,var3,var4,var5,var6) 

public Class B{ 

    private C c; 
    private D d; 

} 

경우 클래스 B (VAR2, VAR3), C (var4로 채워질 것이다 클래스 클래스 A에서 나오는 타측 데이터 반면에 필요한 모든 데이터가 편평한 구조 , var5), D (var6) 등. 또한 벤더 API가 모두 Java 기반이라는 사실을 잊어 버렸습니다.

감사합니다,

+0

너무 넓습니다. 특정 상황을 해결하기 위해 관련된 문제에 대한 적절한 분석은 SO의 범위를 벗어납니다. –

+3

Function1 [A, B]는 A에서 B로 변환합니다. 그 외에는 달성하려는 계산에 대한보다 구체적인 설명없이이 질문에 대답 할 수있는 사람이 누구인지 알 수 없습니다. –

+0

충분합니다. 예를 들어 편집 한 게시물. 추가 설명이 필요한지 알고 있습니다. – user2066049

답변

0

난 당신이 아마 앞뒤로 두 사이 이동합니다 "포주"패턴을 활용할 수 있다고 말할 것입니다. 내 응용 프로그램에서 사용하는 물건이 여기에 있습니다. 한 방향으로 만 변환하지만 다른 암시 적 방법으로 원래/사용자의 형식으로 돌아갈 수있는 논리를 구현할 수있는 방법을 알 수 있습니다.

// implicits for pimping 
implicit def pimpUser(user: User) = PimpedUser(user) 
implicit def pimpLimitedViewUser(user: LimitedViewUser) = PimpedLimitedViewUser(user) 

@entity 
case class User(@serializer(classOf[UUIDOptionSerializer]) @id @column(name = "id") override val id: Option[UUID] = None, 
       @serializer(classOf[DateOptionSerializer]) @column(name = "created_on") override val createdOn: Option[Date] = None, 
       @serializer(classOf[DateOptionSerializer]) @column(name = "modified_on") override val modifiedOn: Option[Date] = None, 
       @serializer(classOf[StringOptionSerializer]) @column(name = "first_name") firstName: Option[String] = None, 
       @serializer(classOf[StringOptionSerializer]) @column(name = "last_name") lastName: Option[String] = None, 
       @serializer(classOf[StringOptionSerializer]) @column(name = "email_address") emailAddress: Option[String] = None, 
       @serializer(classOf[StringOptionSerializer]) @column(name = "password_salt") passwordSalt: Option[String] = None, 
       @serializer(classOf[StringOptionSerializer]) @column(name = "password_hash") passwordHash: Option[String] = None, 
       @serializer(classOf[IntOptionSerializer]) @column(name = "extension") extension: Option[Int] = None, 
       devices: Set[Device] = Set.empty, 
       @serializer(classOf[RingModeSerializer]) @column(name = "ring_mode") ringMode: RingMode = Waterfall) extends IdBaseEntity[UUID] { 
    def this() = this(None, None, None, None, None, None, None, None, None, Set.empty[Device], Waterfall) 

    override def equals(other: Any): Boolean = 
    other match { 
     case that: User => (that canEqual this) && (this.id match { 
     case Some(uuid) => that.id match { 
      case Some(thatUuid) => uuid == thatUuid 
      case None => false 
     } 
     case None => false 
     }) 
     case _ => false 
    } 

    override def hashCode: Int = this.id match { 
    case Some(uuid) => 41 * (41 + uuid.hashCode()) 
    case None => super.hashCode 
    } 

    override def canEqual(other: Any): Boolean = other.isInstanceOf[User] 

    def asAvailable: User = { 
    User.devices.set(this)(devices.map(_.asAvailable)) 
    } 

    def asUnavailable: User = { 
    User.devices.set(this)(devices.map(_.asUnavailable)) 
    } 
} 

object User { 
    implicit val userIso = Iso.hlist(User.apply _, User.unapply _) 

    val id = Lens[User] >> _0 
    val createdOn = Lens[User] >> _1 
    val modifiedOn = Lens[User] >> _2 
    val firstName = Lens[User] >> _3 
    val lastName = Lens[User] >> _4 
    val emailAddress = Lens[User] >> _5 
    val passwordSalt = Lens[User] >> _6 
    val passwordHash = Lens[User] >> _7 
    val extension = Lens[User] >> _8 
    val devices = Lens[User] >> _9 
    val ringMode = Lens[User] >> _10 
} 

case class LimitedViewUser(id: Option[UUID], createdOn: Option[Date], modifiedOn: Option[Date], firstName: Option[String], lastName: Option[String]) { 
    def this(user: User) = this(user.id, user.createdOn, user.modifiedOn, user.firstName, user.lastName) 
} 

case class PimpedUser(underlying: User) { 
    def limited = LimitedViewUser(underlying) 
} 

case class PimpedLimitedViewUser(underlying: LimitedViewUser) { 
    def normal = /* do something here to transform back to yours/the normal one */ 
} 

// As long as those implicits are brought into scope, you will be able to do this: 

val user: User = /* ... */ 
val limitedViewUser: LimitedViewUser = user.limited 
val normalUser: User = limitedViewUser.normal 
관련 문제