简体   繁体   English

这是对适配器模式的正确使用吗? 我无法实例化该对象?

[英]Is this a correct Use Of Adapter Pattern? I can't instantiate this object?

I am using C# with Unity3D. 我在Unity3D中使用C#。

There is an object type called Transform that I cannot directly instantiate. 我无法直接实例化一个名为Transform的对象类型。

I want to do some unit testing on a function that uses Transform. 我想对使用Transform的函数进行一些单元测试。

Is this the correct way to do it? 这是正确的方法吗?

Use the adapter pattern by: 通过以下方式使用适配器模式:

  • creating a class (TransformAdapter) that has the same functionality as Transform 创建具有与Transform相同功能的类(TransformAdapter)
  • (when running for real) extending TransformAdapter, with a class called UnityTransform, that holds a Transform and just forwards on any functionality to Transform. (当实际运行时)使用名为UnityTransform的类扩展TransformAdapter,该类保存Transform并将任何功能转发到Transform。
  • (when running in unit test) extending TransformAdapter, with a class caled MockTransform, that just holds values set by my unit test. (在单元测试中运行时)使用类MockTransform扩展了TransformAdapter,该类仅保存我的单元测试设置的值。

Update: 更新:

It appears that in many situations, I don't need to create abstract classes to mock out the objects, as I can instantiate the objects from unit tests if I run the unit tests from the Unity3d Unit Testing window. 看起来在很多情况下,我不需要创建抽象类来模拟对象,因为如果我从Unity3d单元测试窗口运行单元测试,就可以从单元测试中实例化对象。 I cannot instantiate the objects if running the tests from MonoDevelop. 如果从MonoDevelop运行测试,则无法实例化对象。

Unity3D doesn't really allow you to use your "normal" design patterns because of certain limitations, especially with it's internal serialization. 由于某些限制,尤其是内部序列化,Unity3D确实不允许您使用“常规”设计模式。

But specific to your case, in Unity3D a transform cannot exist without a GameObject, and vice-versa. 但是针对您的情况,在Unity3D中,如果没有GameObject,就无法存在转换,反之亦然。 Just use new GameObject("Insert Name Here") in conjunction with GetComponent() on the new transform. 只需在新转换上将新的GameObject(“ Insert Name Here”)与GetComponent()结合使用即可。 You could write a small factory to do this. 您可以编写一个小型工厂来执行此操作。

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

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