zoukankan      html  css  js  c++  java
  • Java设计模式—工厂设计模式

    工厂设计模式(减少耦合。通过接口或者工厂类来实现)

    耦合性:粘度强(依耐性) Person p = new Person();  //耦合性强

                 Man p = new Person();     //耦合性弱,Man是接口或其它,Person实现这个接口


    简单工厂模式是有一个工厂对象决定创建哪一种产品类的实例。

    简单工厂模式是工厂模式家族中最简单有用的模式.以下给出演示样例代码:


    /**
     * 简单工厂设计模式
     * @author Admin
     *
     */
    public class FactoryDesign {
    
    	public static void main(String[] args) {
    		Car car1 = Factory.getCar("small");     //通过接口来接收对象减少依赖度(耦合性)
    		Car car2 = Factory.getCar("big");
    		if(car1!=null){
    			car1.run();
    		}
    		if(car2!=null){
    			car2.run();
    		}
    	}
    
    }
    
    class Factory{            //工厂类,来间接控制生产对象
    	public static Car getCar(String name){
    		if(name.equals("small")){
    			return new smallCar();      //生产小汽车
    		}else if(name.equals("big")){
    			return new bigCar();       // 生产大汽车
    		}else return null;
    	}
    }
    
    interface Car{
    	public void run();
    }
    class smallCar implements Car{
    	@Override
    	public void run() {
    		System.out.println("小汽车在跑");
    	}
    }
    class bigCar implements Car{
    	@Override
    	public void run() {
    		System.out.println("大汽车在跑");
    	}
    }


    实验结果:








  • 相关阅读:
    【转】IOS开发:[1]Xcode5界面入门
    【转】Xcode中的iOS模拟器(iOS Simulator)的介绍和使用心得
    特征选择
    EM算法
    算法之美--3.2.3 KMP算法
    算法之美--3.2.2 MP算法
    图像质量评价方法PSNR+SSIM&&评估指标SROCC,PLCC
    C/C++二进制读写png文件
    大津法---OTSU算法
    一些优秀的面试笔试总结
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/8379201.html
Copyright © 2011-2022 走看看