标签:应用程序 creat 先来 print ring tin bsp 工厂 extends
1.懒汉模式
public class Singleton {
private Singleton() {};
private static Singleton instance;
private Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2.饿汉模式
public class Singleton2 {
private Singleton2(){};
private static Singleton2 instance=new Singleton2();
public static Singleton2 getInstance(){
return instance;
}
}
简单工厂模式
简单工厂模式又称静态工厂方法模式。重命名上就可以看出这个模式一定很简单。它存在的目的很简单:定义一个用于创建对象的接口。
抽象类产品
public abstract class Animal {
public abstract void eat();
}
具体产品
public class Cat extends Animal{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("Cat");
}
}
具体产品
public class Dog extends Animal {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("Dog");
}
}
工厂类
public class AnimalFactory {
public static Animal creatAnimal(String animal){
if("Dog".equals(animal))
return new Dog();
else if("Cat".equals(animal)){
return new Cat();
}
return null;
}
}
Test
public class TestAimal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog d=(Dog) AnimalFactory.creatAnimal("Dog");
d.eat();
Cat c=(Cat) AnimalFactory.creatAnimal("Cat");
c.eat();
}
}
结果:
Dog
Cat
工厂方法模式
工厂接口
public interface Factory {
public Animal createAnimal();
}
抽象产品
public abstract class Animal {
public abstract void eat();
}
具体工厂
public class CatFactory implements Factory{
@Override
public Animal createAnimal() {
// TODO Auto-generated method stub
return new Cat();
}
}
具体产品
public class Cat extends Animal{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("貓吃魚");
}
}
具体产品
public class Dog extends Animal{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("購入歐好吃不");
}
}
具体工厂
public class DogFactory implements Factory{
@Override
public Animal createAnimal() {
// TODO Auto-generated method stub
return new Dog();
}
}
测试:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Factory f = new DogFactory();
Animal a = f.createAnimal();
a.eat();
Factory c = new CatFactory();
Animal aa = c.createAnimal();
aa.eat();
}
}
结果:
購入歐好吃不
貓吃魚
标签:应用程序 creat 先来 print ring tin bsp 工厂 extends
原文地址:http://www.cnblogs.com/lixiaowei395659729/p/7190105.html