zoukankan      html  css  js  c++  java
  • java 完全解耦

    只要有一个方法操作的是类而非接口,那么你就只能使用这个类及其子类,如果你想要将这个方法应用于不在此继承结构中的某个类,那么你就会触霉头,接口可以在很大程度上放宽这种限制,因此,我们可以编写可服用性更好的代码

    //像本例这样,创建一个能够根据所传递的参数对象的不同而具有不同行为的方法,被称为策略设计
    //策略就是传递进去的参数对象,它包含要执行的代码
    //
    : interfaces/classprocessor/Apply.java package object; import java.util.*; import static net.mindview.util.Print.*; class Processor { public String name() { return getClass().getSimpleName(); } Object process(Object input) { return input; } } class Upcase extends Processor { String process(Object input) { // Covariant return return ((String)input).toUpperCase(); } } class Downcase extends Processor { String process(Object input) { return ((String)input).toLowerCase(); } } class Splitter extends Processor { String process(Object input) { // The split() argument divides a String into pieces: return Arrays.toString(((String)input).split(" "));//split()返回String[]数组 } } public class Apply { public static void process(Processor p, Object s) { print("Using Processor " + p.name()); print(p.process(s)); } public static String s = "Disagreement with beliefs is by definition incorrect"; public static void main(String[] args) { process(new Upcase(), s); process(new Downcase(), s); process(new Splitter(), s); } } /* Output: Using Processor Upcase DISAGREEMENT WITH BELIEFS IS BY DEFINITION INCORRECT Using Processor Downcase disagreement with beliefs is by definition incorrect Using Processor Splitter [Disagreement, with, beliefs, is, by, definition, incorrect] *///:~

    适配器设计模式,设配器的代码将接受你所拥有的接口,并产生你所需要的接口

    //: interfaces/interfaceprocessor/FilterProcessor.java
    package interfaces.interfaceprocessor;
    import interfaces.filters.*;
    
    class FilterAdapter implements Processor {
      Filter filter;
      public FilterAdapter(Filter filter) {  //FilterAapter 接受你拥有的接口Filer
        this.filter = filter;                //然后生成你需要的Processor接口的对象
      }
      public String name() { return filter.name(); }
      public Waveform process(Object input) {
        return filter.process((Waveform)input);
      }
    }    
    
    public class FilterProcessor {
      public static void main(String[] args) {
        Waveform w = new Waveform();
        Apply.process(new FilterAdapter(new LowPass(1.0)), w);
        Apply.process(new FilterAdapter(new HighPass(2.0)), w);
        Apply.process(
          new FilterAdapter(new BandPass(3.0, 4.0)), w);
      }
    } /* Output:
    Using Processor LowPass
    Waveform 0
    Using Processor HighPass
    Waveform 0
    Using Processor BandPass
    Waveform 0
    *///:~
  • 相关阅读:
    《Java课程实习》日志(周二)
    spring helloworld
    [Android L or M ]解除SwitchPreference与Preference的绑定事件
    Smobiler实现列表展示—GridView(开发日志十二)
    LA 4329(树状数组)
    CreateDialog Win32 API调用的一个小问题
    Android Gallery2源代码分析
    你男朋友是程序猿吧
    javaEE之--------统计站点在线人数,安全登录等(观察者设计模式)
    AppFuse 3常见问题与解决方法
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10204990.html
Copyright © 2011-2022 走看看