一个接口Shape:
public interface Shape{
public void showShape();
}
再写几个形状类Rectangle Square Circle 等,以下就以Circle为例
public class Circle implements Shape{
public void showShape(){
System.out.println("My shape : Circle");
}
}
这个就是工厂类
public class ShapeFactory{
String shape;
public ShapeFactory(String shape){
this.shape=shape;
}
public Shape getShape(){
if(this.shape.equals("rectangle")){
return new Circle();
}else if(this.shape.equals("square")){
return new Square();
}else if(this.shape.equals("circle")){
return new Circle();
}else{
return null;
}
}
}
实现代码:
public class Main{
public static void main(String [] args){
Shape circle = new Shape("circle").getShape();
Shape square = new Shape("square").getShape();
Shape rectangle = new shape("rectangle").getShape();
//通过上述代码就能够实现通过工厂模式实现对象的实例化
//这就是比较规范的工厂模式
}
}
下面我再来写写单例模式,
我们知道有些类是不能被实例化的,比如说Math类,要使用它的话,直接 用 Math. 来访问它的方法就 ok了
那么单例模式也与此有异曲同工之妙,
写一个单例模式的SingTestItem类
public class SingTestItem{
public static SingTestItem single=new SingTestItem() ;//实例化一个静态的本类对象,注意,是静态的实例
private SingTestItem(){}//关键是这一步,把构造方法设置权限为私有,这样外部就不能通过构造方法来实例化对象了
public static SingTestItem getInstace(){//通过调用这个方法就能够放回一个对象,这个方法也应该是静态的,才能实现全局只有一个实例
return single;
}
}