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

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();
    }

  • 运行效果如下:

java设计模式 之 抽象工厂模式_第1张图片

你可能感兴趣的:(java,设计模式,android,抽象工场模式)