- 简单模式
自主选择零件,自由搭配
- Cpu、MainBoard接口,进行多态
public interface MainBoard {
}
public interface Cpu {
}
2.实现接口
public class IntelCpu implements Cpu {
}
public class AmdCpu implements Cpu {
}
public class IntelMainBoard implements MainBoard {
}
public class AmdMainBoard implements MainBoard {
}
3.创建工厂类
public class CpuFactory {
Cpu cpu;
public Cpu Craet(int i) {
if(i==1) {
cpu=new IntelCpu();
System.out.println("intel cpu");
}else {
cpu=new AmdCpu();
System.out.println("amd cpu");
}
return cpu;
}
}
public class MainBoardFactory {
MainBoard mb;
public MainBoard Craet(int i) {
if(i==1) {
mb=new IntelMainBoard();
System.out.println("intel md");
}else {
mb=new AmdMainBoard();
System.out.println("intel md");
}
return mb;
}
}
4.生产电脑
public class Computer {
public void creatcomputer(int i,int j) {
CpuFactory cpu=new CpuFactory();
cpu.Craet(i);
MainBoardFactory mb=new MainBoardFactory();
mb.Craet(j);
}
}
5.传递参数,调用方法开始生产
public class Client {
public static void main(String[] args) {
Computer comp=new Computer();
comp.creatcomputer(2,1);
}
}
抽象工厂
interface Cpu{
}
interface MainBoard{
}
class IntelCpu implements Cpu{
}
class AmdCpu implements Cpu{
}
class IntelMainBoard implements MainBoard{
}
class AmdMainBoard implements MainBoard{
}
interface AbstractFactory {
Cpu creatCpu();
MainBoard creatMainboard();
}
class IntelFactory implements AbstractFactory{
@Override
public Cpu creatCpu() {
// TODO Auto-generated method stub
return new IntelCpu();
}
@Override
public MainBoard creatMainboard() {
// TODO Auto-generated method stub
return new IntelMainBoard();
}
}
class AmdFactory implements AbstractFactory{
@Override
public Cpu creatCpu() {
// TODO Auto-generated method stub
return new AmdCpu();
}
@Override
public MainBoard creatMainboard() {
// TODO Auto-generated method stub
return new AmdMainBoard();
}
}
class Computer{
public void creatComper(int i) {
AbstractFactory comp;
if(i==1) {
comp=new IntelFactory();
comp.creatCpu();
comp.creatMainboard();
}
else if(i==2) {
comp=new IntelFactory();
comp.creatCpu();
comp.creatMainboard();
}
}
}
public class Client {
public static void main(String[] args) {
Computer comp=new Computer();
comp.creatComper(2);
}
}