zoukankan      html  css  js  c++  java
  • 简单工厂模式学习

    简单工厂模式

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

    // 测试类,包含main方法
    public class FactoryPattern {
    
    	public static void main(String[] args) {
    		// 不使用工厂模式时,使用者和被使用者之间耦合,产生了依赖,
    		// 当被使用这改变时,会影响使用者。使用工厂模式来降低两者之间的依赖。
    		Product phone = new Phone();
    		phone.work();
    
    		// 当增加工厂类时,现在我们调用方式变了,通过新增工厂类,降低了使用者和被使用者之间的依赖
    		Product phone1 = ProductFactory.getProduct("phone");
    		if (null != phone1) {
    			phone1.work();
    		}
    	}
    }
    
    // 接口定义了产品应具有工作的行为
    interface Product {
    	public void work();
    }
    
    // 实现类一
    class Phone implements Product {
    	@Override
    	public void work() {
    		System.out.println("手机工作");
    	}
    }
    
    // 实现类二
    class Computer implements Product {
    	@Override
    	public void work() {
    		System.out.println("电脑工作");
    	}
    }
    
    //新增加工厂类
    class ProductFactory {
    	public static Product getProduct(String productName) {
    		if ("phone".equals(productName)) {
    			return new Phone();
    		} else if ("computer".equals(productName)) {
    			return new Computer();
    		} else {
    			return null;
    		}
    	}
    }
  • 相关阅读:
    IBatis简介
    cntlm代理使用
    bash快捷键你知道几个?
    django的Form中添加属性
    EMACS 中文显示为方框
    git合并子树
    算法 排序 python 实现堆排序
    android org.eclipse.wst.sse.core 0.0.0' but it could not be found
    我的EMACS配置
    python 输入# 自动跳到行首
  • 原文地址:https://www.cnblogs.com/zxfei/p/10850673.html
Copyright © 2011-2022 走看看