我们可以在运行时分配/改变scala类的特性吗?如何 - 任何示例代码?像战略模式(四个设计模式的帮派) [英] Can we assign / change traits to the scala class during runtime? How - any sample code? Like Strategy Pattern (of Gang of four Design Pattern)

查看:131
本文介绍了我们可以在运行时分配/改变scala类的特性吗?如何 - 任何示例代码?像战略模式(四个设计模式的帮派)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解释我的问题:



类:玩具



Trait1:像男性说话



Trait2:说话像女性



我可以在运行时改变玩具的行为(traits),有时候同一个对象说男性有时候同样的对象就像女性?



我想在运行时改变说话行为。

解决方案

Scala真的不这样做。有凯文·赖特的自动插件可以做到这一点,你可以实例化并使用特征进行对象,而没有这个特征是基类的一部分。



<我个人认为,试图通过这种方式来完成这件事情就是要反对斯卡拉的粮食:坚硬而容易被卡住。最好设计一个不需要这样的东西的解决方案 - 事实上,Scala粒子往往更多的是功能性的,它把重点放在一切都是不可变的上,并且通过计算来替换一个对象。


To explain my question:

Class : Toy

Trait1: Speak like Male

Trait2: Speak like Female

Can I change the behavior (traits) of Toy during runtime so sometimes the same object speaks like male and sometimes the same object speaks like female?

I want to change the speaking behavior at runtime.

解决方案

Scala really doesn't do that. There's Kevin Wright's autoproxy plugin which can do it, and you can instantiate and object with either trait, without that trait being part of the base class.

I personally think that trying to accomplish things that way is to go against the grain of Scala: hard and prone to getting stuck. It is better to design a solution that doesn't require such things -- in fact, Scala grain tends much more to the functional, which put focus on everything being immutable, and replacing one object with a new one as a result of computation.

这篇关于我们可以在运行时分配/改变scala类的特性吗?如何 - 任何示例代码?像战略模式(四个设计模式的帮派)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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