`

工厂模式

    博客分类:
  • java
阅读更多

1.单例模式和protected\private构造方法

使用了protected,客户程序(不在同一包内)就不能随便创建该类的一个实例了.但是由于是protected,使得该类可以被继承.

如果构造函数是私有的,那么该类无法被继承(因为子类构造时要调用超类的构造函数,而private使得子类无法调用),无法从外界获得一个对象.但是可以在类的内部产生一个实例的,例如singleton就是使用private的构造函数,然后在内部维护一个实例,而提供一个static的getInstance方法来获取这个实例

 

public class  Car(){

 

private Car(){}                               //私有化的构造方法,限制其他人new car,只有Car自己能new

private static Car car=new Car();  //Car内部new car

 

public static Car getInatance()   //getInstance是工厂模式 是生产car的工厂,由于是静态的,所以是静态工厂模式

{return car;}                              //方法内部可以自己控制生产的方法

 

}

 

测试类

public classTestCar(){

Car car=Car.getInstance();

Car car2=Car.getInstance();

if(car==car2){System.out.println("true");}  //结果true;说明是同一个实例

 

}


如果构造函数是protected,那么该类可以继承,可以在被包内其他类中产生实例,但是无法在包外或者子类以外的地方产生实例.
public就不说了.

 

2.多例模式,多态

public class  Car(){

 

private Car(){}                               //私有化的构造方法,限制其他人new car,只有Car自己能new

private static List<Car> cars=new ArrayList<Car>();  //多例模式 

public static Car getInatance()   //getInstance是工厂模式 是生产car的工厂,由于是静态的,所以是静态工厂模式

{return cars.get(0);}                              //可以随意取一个实例 

}

交通工具和工厂的例子

public interface Moveable(){

    void run(){}                  //interface内部的方法默认是public

     }

 

public class Car implements Moveable(){   //Car类

 

     public viod run(){System.out.println("this is a car.");}

     }

 

public class Plane implements Moveable(){  //plane类

     public viod run(){System.out.println("this is a plane.");}

     }

public abstract class VehicleFactory(){     //vehicleFactory抽象类

public Moveable create(){};

}

 

public class CarFactory extends VehicleFactory(){

public Moveable create(){return new Car();};

}

 

//测试类

public class Test(){

public void main(String[] args){

VehicleFactory f=new CarFactory();

Moveable m=f.create();

m.run();

}

 

}

 

//抽象类和接口很类似,某概念确实存在的,用抽象类。如果只是某一类特性和功能时用接口。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics