您的位置:首页 > 编程语言 > Java开发

工厂方法模式(设计模式_08)

2016-12-15 19:02 267 查看
工厂方法模式遵循了,开放封闭式原则,我们直接用案例来体现:

// 定义一个电脑接口
public interface IComputer {

// 获取电脑组件的方法
public void myStyle();

}

// 电脑适配器实现电脑接口
public class Adapter implements IComputer{

public void myStyle() {
System.out.println("这是电脑的充电器....");
}

}

// 电脑主板实现电脑
public class Board implements IComputer {

public void myStyle() {
System.out.println("这是电脑主板...");
}

}

// 显示屏类实现电脑
public class Display implements IComputer{

public void myStyle() {
System.out.println("这是电脑显示屏...");
}

}


此时切换到工厂方法模式区域

// 定义工厂接口,此工厂接口可以制作很多东西,例如 电脑,平板,手机,等等....

public interface IFactory {

/**
* 定义制造电脑的函数
* @return 返回电脑接口
*/
public IComputer getComputer();

}

// 工厂实现工厂接口
public class Factory implements IFactory {

public IComputer getComputer() {
// 这个Computer类,下面区域有介绍到
return new Computer(new Display(), new Board(), new Adapter());
}

}

// Computer类
// 电脑类实现电脑接口 == 一台电脑
public class Computer implements IComputer{

// public Computer(){};

private Display engine;
private Board underpan;
private Adapter wheel;

public Computer(Display engine, Board underpan, Adapter wheel){
this.engine = engine;
this.underpan = underpan;
this.wheel = wheel;
}

public void myStyle() {
engine.myStyle();
underpan.myStyle();
wheel.myStyle();
}

}

// 客户端程序
public class Main {

public static void main(String [] args) {

// 得到工厂
IFactory factory = new Factory();

// 调用工厂去制作电脑
IComputer car = factory.getComputer();

car.myStyle();

}

}


运行结果:



谢谢大家的观看,更多精彩技术博客,会不断的更新,请大家访问,

刘德利CSDN博客, http://blog.csdn.net/u011967006
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息