单利模式
###懒汉式###
public class Human{
public staic Human human=null;
public Human getHuman(){
if(human==null){
human=new Human();
}
return human;
}
}
###饿汉式###
public class Human{
public staic Human human=new Human();
public Human getHuman(){
return human;
}
}
工厂模式
//创建实例的工厂
public interface FruitsFactory{
Fruit getFruit();
}
public class AppleFactory implements FruitsFactory{
public Fruit getFruit(){
return new Apple();
}
}
public class BananaFactory implements FruitsFactory{
public Fruit getFruit(){
return new Banana();
}
}
//具体创建的实例对象
public interface Fruit{
void Color();
}
public class Apple implements Fruit{
public void getColor(){
System.out.println("The apple's color is red!");
}
}
public class Banana implements Fruit{
public void getColor(){
System.out.println("The banana's color is yellow!");
}
}
//测试类
public class Test{
public static void main(String args[]){
FruitsFactory fruitsFactory=new AppleFactory();
Apple apple=fruitsFactory.getFuit();
apple.getColor();
FruitsFactory fruitsFactory=new BananaFactory();
Banana banana=fruitsFactory.getFuit();
banana.getColor();
}
}
结果:
- The apple’s color is red!
- The banana’s color is yellow!