接口的设计应用
1.把可变的行为抽象出来,这样的好处是在真正的时候可以相互替换
接口就是定义行为的
首先如果要 要把某个具体功能提取出来,那么就先把这个功能给弄成策略
inteface xxx,然后各自具体用 类去继承这个接口(class FileSave implements xxx,class NetworkSave implements xxx)
以上过程就是策略。
从哪里来就到哪里去,在提取的接口的类中去把接口封装,把接口变成属性。
然后在提取的类中选择你要实现的功能。
少用继承,会把不用的继承给继承下来
public class TestFactory { public static void main(String[] args) { // TODO Auto-generated method stub Product p = new ProductFactory().getProduct("phone"); p.Work(); } } interface Product{ public void Work(); } class Phone implements Product{ public void Work() { System.out.println("手机开始工作。。"); } } class Computer implements Product{ public void Work() { System.out.println("电脑开始工作。。"); } } class ProductFactory{ // Product phone = new Phone(); public Product getProduct(String name) { if ("phone".equals(name)) { return new Phone(); } else return new Computer(); } }