码迷,mamicode.com
首页 > 其他好文 > 详细

Scala学习之延迟绑定

时间:2015-12-25 23:42:25      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

 1 package com.swust.example
 2  
 3 object TraitDemo2 extends App{
 4  
 5    //抽象类
 6      abstract class Writer {
 7         def writeMessage(message: String)
 8      }
 9      /**
10       * 继承这个抽象类,并且用super调用了这个抽象方法
11       * scala要求将方法声明为abstract override
12       * override告诉scala要为基类的一个已知方法提供一个实现
13       * abstract表示这个方法实际最后的终极实现要由混入这个trait的类提供
14       */
15      trait UpperCaseWriter extends Writer{
16         abstract override def writeMessage(message: String)={
17            super.writeMessage(message.toUpperCase)
18         }
19      }
20      /**
21       * 为了调用super.writeMessage,scala做了两件事情
22       * 1、对这个调用进行了延迟绑定
23       * 2、要求混入这些trait的类提供该方法的实现
24       */
25      trait WordFilterWriter extends Writer{
26         abstract override def writeMessage(message: String)={
27            super.writeMessage(message.replace("stupid","s-----"))
28         }
29      }
30      class StringWriterDelegate extends Writer{
31         val writer = new java.io.StringWriter
32         //实现抽象类的方法,不用override
33         def writeMessage(message: String) = writer.write(message)
34         override def toString(): String = writer.toString
35      }
36      //创建实例时混入trait
37      val first = new StringWriterDelegate with UpperCaseWriter with WordFilterWriter
38      val last = new StringWriterDelegate with WordFilterWriter with UpperCaseWriter
39      first.writeMessage("there is no sin except stupidity")
40      last.writeMessage("there is no sin except stupidity")
41      println(first)
42      println(last)
43       
44 }

 

Scala学习之延迟绑定

标签:

原文地址:http://www.cnblogs.com/sunfie/p/5077262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!