java编程思想读书笔记一

2017-05-11  本文已影响128人  yueyue_projects

多态

接口

内部类

2.创建内部类后,使用变量是比较灵活,方便的,通过迭代器模式就能够看出来

  1. 可独立可有联系,更灵活.
  2. 方便组织有一定逻辑关系的类。

持有对象

public class Base {
    private String baseName = "base";
    public Base()
    {
        callName();
    }
    public void callName()
    {
        System.out.println(baseName);
    }    
    public void f1(){
        System.out.println("f1");
    }
     public static void main(String[] args)
     {
         Base b = new Sub();
         b.callName();
         //在编译期就认为是Base,而在运行时则转化为确定的对象
         //b.extraMethod()
     }
}
class Sub extends Base
{
    private String baseName = "sub";
    public void callName()
    {
        System.out.println (baseName) ;
    }
    public void extraMethod(){
        System.out.println("extraMethod");
    }
    public void f2(){
        System.out.println("f2");
    }
}

字符串

RTTI(类型信息)

```java
//: typeinfo/Shapes.java
 import java.util.*;

 abstract class Shape {
   void draw() { System.out.println(this + ".draw()"); }
   abstract public String toString();
 }

 class Circle extends Shape {
   public String toString() { return "Circle"; }
 }

 class Square extends Shape {
   public String toString() { return "Square"; }
 }

 class Triangle extends Shape {
   public String toString() { return "Triangle"; }
 }  

 public class Shapes {
   public static void main(String[] args) {
     List<Shape> shapeList = Arrays.asList(
       new Circle(), new Square(), new Triangle()
     );
     for(Shape shape : shapeList)
       shape.draw();
   }
 } /* Output:
 Circle.draw()
 Square.draw()
 Triangle.draw()
 *///:~
```
 在编译时,具体形状都向上转型为`Shape`类型了,方法也只能调用`Shape`类的方法,但在运行时,可以识别出具体的类型信息。
```java
package com.typeinfo;

   //: typeinfo/RegisteredFactories.java
   // Registering Class Factories in the base class.
   import java.util.*;

   import com.typeinfo.Factory;

   interface Factory<T> { T create(); } ///:~

   class Part {
     /**
     * 模板+RTTI方法
     */
    public String toString() {
        return getClass().getSimpleName();
    }
    static List<Class<? extends Part>> partClasses = 
        new ArrayList<Class<? extends Part>>();
    static {
        //创建类字面变量,利用newInstance()方法使其不用再类里面显示调用构造器
        partClasses.add(FuelFilter.class);
        partClasses.add(AirFilter.class);
        partClasses.add(CabinAirFilter.class);
        partClasses.add(OilFilter.class);
        partClasses.add(FanBelt.class);
        partClasses.add(PowerSteeringBelt.class);
        partClasses.add(GeneratorBelt.class);
    }
    private static Random rand = new Random();
    public static Part createRandom() {
        int n = rand.nextInt(partClasses.size());
        try {
            return partClasses.get(n).newInstance();
        } catch(InstantiationException e) {
            throw new RuntimeException(e);
        } catch(IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    } 
     /**
     * 模板+构造器方法
     */
   //  public String toString() {
   //    return getClass().getSimpleName();
   //  }
   //  static List<Factory<? extends Part>> partFactories =
   //    new ArrayList<Factory<? extends Part>>();  
   //  static {
   //    // Collections.addAll() gives an "unchecked generic
   //    // array creation ... for varargs parameter" warning.
   //    partFactories.add(new FuelFilter.Factory());
   //    partFactories.add(new AirFilter.Factory());
   //    partFactories.add(new CabinAirFilter.Factory());
   //    partFactories.add(new OilFilter.Factory());
   //    partFactories.add(new FanBelt.Factory());
   //    partFactories.add(new PowerSteeringBelt.Factory());
   //    partFactories.add(new GeneratorBelt.Factory());
   //  }
   //  private static Random rand = new Random(47);
   //  public static Part createRandom() {
   //    int n = rand.nextInt(partFactories.size());
   //    return partFactories.get(n).create();
   //  }
   }    

   class Filter extends Part {}

   class FuelFilter extends Filter {
     // Create a Class Factory for each specific type:
     public static class Factory
     implements com.typeinfo.Factory<FuelFilter> {
       public FuelFilter create() { 
        return new FuelFilter(); 
       }
     }
   }

   class AirFilter extends Filter {
     public static class Factory
     implements com.typeinfo.Factory<AirFilter> {
       public AirFilter create() { return new AirFilter(); }
     }
   }    

   class CabinAirFilter extends Filter {
     public static class Factory
     implements com.typeinfo.Factory<CabinAirFilter>{
       public CabinAirFilter create() {
         return new CabinAirFilter();
       }
     }
   }

   class OilFilter extends Filter {
     public static class Factory
     implements com.typeinfo.Factory<OilFilter> {
       public OilFilter create() { return new OilFilter(); }
     }
   }    

   class Belt extends Part {}

   class FanBelt extends Belt {
     public static class Factory
     implements com.typeinfo.Factory<FanBelt> {
       public FanBelt create() { return new FanBelt(); }
     }
   }

   class GeneratorBelt extends Belt {
     public static class Factory
     implements com.typeinfo.Factory<GeneratorBelt> {
       public GeneratorBelt create() {
         return new GeneratorBelt();
       }
     }
   }    

   class PowerSteeringBelt extends Belt {
     public static class Factory
     implements com.typeinfo.Factory<PowerSteeringBelt> {
       public PowerSteeringBelt create() {
         return new PowerSteeringBelt();
       }
     }
   }    

   public class RegisteredFactories {
     public static void main(String[] args) {
       for(int i = 0; i < 10; i++)
         System.out.println(Part.createRandom());
     }
   } /* Output:
   GeneratorBelt
   CabinAirFilter
   GeneratorBelt
   AirFilter
   PowerSteeringBelt
   CabinAirFilter
   FuelFilter
   PowerSteeringBelt
   PowerSteeringBelt
   FuelFilter
   *///:~
```
```java
    interface Book {
     // 判断Book对象是否为空对象(Null Object)
     public boolean isNull();
     // 展示Book对象的信息内容。
     public void show();
 }
 public class NullBook implements Book {
     public boolean isNull() {
         return true;
     }
     public void show() {
     }
 }
  public class ConcreteBook implements Book{
     private int ID;
     private String name;
     private String author;
     // 构造函数
     public ConcreteBook(int ID, String name, String author) {
         this.ID = ID;
         this.name = name;
         this.author = author;
     }
      /**
      *Description About show
      *展示图书的相关信息
      */
     public void show() {
       System.out.println(ID + "**" + name + "**" + author);
    }
    public boolean isNull(){
      return false;
    }
 }
```
```java
public class BookFactory {
   /**
   *根据ConcreteBook的ID,获取图书对象。
   *@param ID 图书的ID
   *@return 图书对象
   */
  public Book getBook(int ID) {
      Book book;//将原来的ConcreteBook改为Book
      switch (ID) {
      case 1:
          book = new ConcreteBook(ID, "设计模式", "GoF");
          break;
      case 2:
          book = new ConcreteBook(ID, "被遗忘的设计模式", "Null Object Pattern");
          break;
      default:
          book = new NullBook();//创建一个NullBook对象
          break;
      }
      return book;
  }
 }
```
```java
 public static void main(String[] args) {
      BookFactory bookFactory = new BookFactory();
      Book book = bookFactory.getBook(-1);
      book.show();
  }
```
  (?)接着是利用动态代理模式+对象模式的改版,***但这个例子不能让我明白它的好处***,例子如下:

```java
 package com.typeinfo;
   import java.lang.reflect.InvocationHandler;
   import java.lang.reflect.Method;
   import java.lang.reflect.Proxy;
   interface Book {
       // 判断Book对象是否为空对象(Null Object)
       public boolean isNull();
       // 展示Book对象的信息内容。
       public void show();
   }
   class NullBookProxyHandler implements InvocationHandler{
    private Class<? extends Book> mType;
    private Book proxyied = new NullBook();//指定了动态产生的代理实例
    public NullBookProxyHandler(Class<? extends Book> type){
        mType = type;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // TODO Auto-generated method stub
        System.out.println(mType);
        return method.invoke(proxyied, args);
    }
    public class NullBook implements Book {
        public boolean isNull() {
            return true;
        }
        public void show() {
            System.out.println("对不起,查之无物");
        }
    }
   }

   public class NullPattern {
    public static Book newNullBook(Class<? extends Book> type){
        return (Book)Proxy.newProxyInstance(NullPattern.class.getClassLoader(), new Class[]{Book.class}, new NullBookProxyHandler(type));   
    }
    public class ConcreteBook implements Book{
        private int ID;
        private String name;
        private String author;
        // 构造函数
        public ConcreteBook(int ID, String name, String author) {
            this.ID = ID;
            this.name = name;
            this.author = author;
        }
        public void show() {
            System.out.println(ID + "**" + name + "**" + author);
        }
        public boolean isNull(){
            return false;
        }
    }
    public class BookFactory {
        public Book getBook(int ID) {
            Book book = newNullBook(ConcreteBook.class);//将原来的ConcreteBook改为Book
            switch (ID) {
            case 1:
                book = new ConcreteBook(ID, "设计模式", "GoF");
                break;
            case 2:
                book = new ConcreteBook(ID, "被遗忘的设计模式", "Null Object Pattern");
                break;
            default:
                //book = ;
                break;
            }
            return book;
        }
    }
    public BookFactory create(){
        return new BookFactory();
    }
    public static void main(String[] args) {
        NullPattern np = new NullPattern();
        BookFactory bookFactory = np.create();
        Book book = bookFactory.getBook(-1);
        book.show();
    }
   }
```
上一篇下一篇

猜你喜欢

热点阅读