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

java设计模式 之 抽象工厂模式

2013-11-26 14:53 369 查看

java设计模式 之 抽象工厂模式

抽象工厂模式:解决了工厂模式的弊端,当新加一个功能的时候,不会影响之前的代码。

接口 IMobile 代码如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package Factory;

/**
*
* @author dev
*/
public interface IMobile {
public void printName();
}


实现类 IPhoneMobile 代码如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package Factory;

/**
*
* @author dev
*/
public class IPhoneMobile implements IMobile {

@Override
public void printName() {
System.out.println("我是一个iPhone手机!");
}

}


实现类 SamsungMobile 代码如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package Factory;

/**
*
* @author dev
*/
public class SamsungMobile implements IMobile {

@Override
public void printName() {
System.out.println("我是一个三星手机!");
}
}


接口 IFactory 代码如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package Factory;

/**
*
* @author dev
*/
public interface IFactory {
public IMobile produce();
}


IPhone手机工场类 IPhoneFactory 代码如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package Factory;

/**
*
* @author dev
*/
public class IPhoneFactory implements IFactory {

@Override
public IMobile produce() {
return new IPhoneMobile();
}
}


三星手机工场类 SamsungFactory 代码如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package Factory;

/**
*
* @author dev
*/
public class SamsungMobile implements IMobile {

@Override
public void printName() {
System.out.println("我是一个三星手机!");
}
}


最后,main 函数如下:

public static void main(String[] args) {
// TODO code application logic here
IFactory factory = new IPhoneFactory();
IMobile iphone = factory.produce();
iphone.printName();
}


运行效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: