工厂模式

一、实验目的:

1) 掌握工厂模式(Factory)的特点

2) 分析具体问题,使用工厂模式进行设计

二、实验环境:

Eclipse

 三、实验内容:

(写出主要的内容)

有一个OEM制造商代理做HP笔记本电脑(Laptop),后来该制造商得到了更多的品牌笔记本电脑的订单Acer,Lenovo,Dell,该OEM商发现,如果一次同时做很多个牌子的本本,有些不利于管理。利用工厂模式改善设计,用JAVA语言实现  (C#控制台应用程序实现)该OEM制造商的工厂模式。绘制该模式的UML图。

模式UML

 
 

【模式代码(JAVA语言实现)】

public interface Computer {
    public void computerType();
}
public class Acer implements Computer {
    public void computerType(){
        System.out.println("类型是Acer");
    }
}
public class Dell implements Computer {
    public void computerType(){
        System.out.println("类型是Dell");
    }
}
public class Lenvo implements Computer {
    public void computerType(){
        System.out.println("类型是Lenvo");
    }
}
public interface ComputerFactory {
    public Computer getComputerType();
}
public class AcerFactory implements ComputerFactory {
    public Computer getComputerType(){
        return new Acer();
        
    }
}
public class DellFactory implements ComputerFactory {
    public Computer getComputerType(){
        return new Dell();
        
    }
}
public class LenvoFactory implements ComputerFactory {
    public Computer getComputerType(){
        return new Lenvo() ;
        
    }
}
public class Client {
        private static ComputerFactory Dell1, lenvo2, Acer3;
        private static Computer cp1, cp2, cp3;
     public static void main(String[] args)
        {
            Dell1 = new DellFactory();
            cp1 = Dell1.getComputerType();
            cp1.computerType();

            lenvo2=new LenvoFactory();
            cp2=lenvo2.getComputerType();
            cp2.computerType();

            Acer3=new  AcerFactory();
            cp3=Acer3.getComputerType();
            cp3.computerType();
        }
    }

 

运行截图

四、心得体会:

通过这次实验掌握工厂模式(Factory)的特点,分析具体问题,使用工厂模式进行设计

 

 

posted on 2019-03-30 22:24  马家升  阅读(154)  评论(0编辑  收藏  举报