Thinking in Java 4th chap9笔记-接口(三)
length();
}
public static void main(Stringargs)
{
Scanner scanner = new Scanner(new AdaptedRandomDoubles(3));
while(scanner.hasNextDouble())
{
System.out.println(scanner.nextDouble() + " ");
}
}
}
/**
*
* 一个要被作用于Scanner的类,用来随机产生doubles
*
* @author landon
*
*/
class RandomDoubles
{
private static Random random = new Random(3);
public double next()
{
return random.nextDouble();
}
}
package com.book.chap9.Interface;
/**
*
*接口的使用
*
*灵活性,可以被依次被向上转型为每个接口
*
*@author landon
*@since JDK1.6
*@version 1.0 2012-5-7
*
*/
public class Adventure
{
public static void t(CanFight t)
{
t.fight();
}
public static void u(CanSwim u)
{
u.swim();
}
public static void v(CanFly v)
{
v.fly();
}
public static void w(ActionCharacter w)
{
w.fight();
}
public static void main(Stringargs)
{
Hero hero = new Hero();
//被向上转型为了接口
t(hero);
u(hero);
v(hero);
w(hero);
}
}
interface CanFight
{
void fight();
}
interface CanSwim
{
void swim();
}
interface CanFly
{
void fly();
}
class ActionCharacter
{
public void fight()
{
}
}
//注: 因为Hero继承了Character类,所以默认有fight方法,所以相当于实现了CanFight接口
class Hero extends ActionCharacter implements CanFight,CanSwim,CanFly
{
@Override
public void fly()
{
}
@Override
public void swim()
{
}
}
package com.book.chap9.Interface;
import java.util.Arrays;
/**
*
*操作类而不是接口的方式
*
*创建一个能够根据所传递的对象的参数不同而具有不同行为的方法,被称为策略设计模式。这类方法包含的所要执行的算法中固定不变的部分,
*而策略包含变化的部分,策略就是传递进去的参数对象 ,它包含要执行的代码。
*
*
*1.Filter接口与Processor具有相同的接口,但是因为它不不是继承自Processor,因为filter类的创建者压根不清楚你想要将它作用于Processor,因此你
*不能将Filter接口应用于Apply的process方法。
*
*2.如果我们把Processor改为一个接口呢
*
*{@link NewApply}
*
*
*@author landon
*@since JDK1.6
*@version 1.0 2012-5-3
*
*/
public class Apply
{
public static void process(Processor processor,Object s)
{
System.out.println("Using Processor: " + processor.name());
System.out.println(processor.process(s));
}
public static String s = "I'm tracy mcgrady";
public static void main(Stringargs)
{
process(new Upcase(), s);
process(new DownCase(), s);
process(new Spliter(), s);
}
}
//Processor
class Processor
{
public String name()
{
return getClass().getSimpleName();
}
Object process(Object input)
{
return input;
}
}
//大写处理器
class Upcase extends Processor
{
//注意这里是协变返回类型
@Override
String process(Object input)
{
return ((String)input).toUpperCase();
}
}
//小写处理器
class DownCase extends Processor
{
//注意这里是协变返回类型
@Override
String process(Object input)
{
return ((String)input).toLowerCase();
}
}
//字符串切