JAVA的简单工厂

JAVA的简单工厂,第1张

一.简单工厂的定义:

简易工厂(Simple Factory)又被称为静态工厂,是通过创建一个工厂类来负责创建其他类,被创建的类通常有着同一个父类。

下面举一个实例:

package factory;

import com.sun.deploy.uitoolkit.impl.awt.AppletCompatibleHost;

public abstract class factory1
{
    public abstract void run();
}
//定义一个名为factory1的抽象父类
class BaomaCarfactory extends factory1 
{
    private String name;

    public BaomaCarfactory(String name);

    {
        this.name = name;
    }

public void run() 
{
        System.out.println(this.name);
    }
}

class Benchifactory extends factory1
 {
    private String name;
    
public Benchifactory(String name)
 {
        this.name = name;
    }

    @Override
    
public void run()
 {
        System.out.println(this.name);
    }
}
//创建两个子类并且继承父类factory1
class Carfactory 
{

public static factory1 createCar(String brand) 
{
        factory1 car = null;
        switch (brand) 

{           
case"benchi":
                factory1 = new Benchifactory(brand);
                break;
            
case "baoma"
         factory1 = new BaomaCarfactory(brand);
                break;
        }
        return factory1;
    }
}
//创建车工厂类。
public class MainActivity extends AppletCompatibleHost 
{
    
protected void onCreate(Bundle savedInstanceState) 
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        factory1 car = Carfactory.createCar("baoma");
        car1.run();
        factory1 car = Carfactory.createCar("benchi");
        car2.run();
    }
}
//定义测试类
System.out:baoma
System.out:benchi
//输出结果

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/877570.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存