/**
* 书本:《Thinking In Java》
* 功能:适配器设计模式
* 文件:Processor.java
* 时间:2015年4月2日20:36:59
* 作者:cutter_point
*/
package Lesson9Interfaces.interfaceprocessor;
public interface Processor
{
String name();
Object process(Object input);
}
/**
* 书本:《Thinking In Java》
* 功能:适配器设计模式
* 文件:Apply.java
* 时间:2015年4月2日20:36:59
* 作者:cutter_point
*/
package Lesson9Interfaces.interfaceprocessor;
import static net.mindview.util.Print.*;
public class Apply
{
public static void process(Processor p, Object s)
{
print("Using Processor " + p.name());
print(p.process(s));
}
}
/**
* 书本:《Thinking In Java》
* 功能:适配器设计模式
* 文件:StringProcessor.java
* 时间:2015年4月2日20:36:59
* 作者:cutter_point
*/
package Lesson9Interfaces.interfaceprocessor;
import java.util.Arrays;
public abstract class StringProcessor implements Processor {
@Override
public String name()
{
return this.getClass().getSimpleName();
}
@Override
public abstract String process(Object input);
public static String s = "If she weights the same as a duck, she`s made of wood";
public static void main(String [] args)
{
Apply.process(new Upcase(), s);
Apply.process(new Downcase(), s);
Apply.process(new Splitter(), s);
}
}
class Upcase extends StringProcessor
{
public String process(Object input)
{
return ((String) input).toUpperCase();
}
}
class Downcase extends StringProcessor
{
public String process(Object input)
{
return ((String) input).toLowerCase();
}
}
class Splitter extends StringProcessor
{
public String process(Object input)
{
return Arrays.toString( ( (String) input).split(" "));
}
}
上一篇里面说过,那两个类耦合太高了,我们如何解耦就在这篇里面,我们可以吧Processor类写成接口,这样用一个抽象类实现这个接口,那么耦合就会变得松动,那么Apply.process()就可以得到复用,接收一个Object参数!!!
输出结果:
Using Processor Upcase obj1
IF SHE WEIGHTS THE SAME AS A DUCK, SHE`S MADE OF WOOD obj1
Using Processor Downcase obj1
if she weights the same as a duck, she`s made of wood obj1
Using Processor Splitter obj1
[If, she, weights, the, same, as, a, duck,, she`s, made, of, wood] obj1