Coffee咖啡
package com.jsu.ch;
public abstract class Coffee {
public abstract String getName();
}
package com.jsu.ch;
public class Latte extends Coffee{
@Override
public String getName() {
return "Black";
}
}
package com.jsu.ch;
public class BlackCoffee extends Coffee{
@Override
public String getName() {
return "Black";
}
}
package com.jsu.ch;
public class CoffeeFactory {
public Coffee creatCoffee(String type) {
Coffee coffee = null;
if("Black".equals(type)){
coffee = new BlackCoffee();
} else if("Latte".equals(type)){
coffee = new Latte();
} else {
System.out.println("没有该种类的咖啡");
}
return coffee;
}
}
package com.jsu.ch;
public class CoffeeStore {
CoffeeFactory factory = new CoffeeFactory();
public Coffee orderCoffee(String type){
Coffee coffee = factory.creatCoffee(type);
return coffee;
}
}
package com.jsu;
import com.jsu.ch.Coffee;
import com.jsu.ch.CoffeeFactory;
import com.jsu.ch.CoffeeStore;
public class Test {
public static void main(String[] args) {
CoffeeStore store = new CoffeeStore();
Coffee coffee = store.orderCoffee("Black");
System.out.println("你的" + coffee.getName() + "制作好了");
}
}
结果展示:
接口interface
package com.jsu.ch;
public interface IControllor {//函数式接口
void open();
}
package com.jsu.ch;
public class RemoteControllor implements IControllor{
@Override
public void open() {
System.out.println("用电视遥控器打开");
}
}
package com.jsu.ch;
public class ToyControllor implements IControllor{
@Override
public void open() {
System.out.println("用玩具遥控器打开");
}
}
package com.jsu.ch;
public class RocketContollor implements IControllor{
@Override
public void open() {
System.out.println("用火箭遥控器打开");
}
}
package com.jsu.ch;
public class Mind implements IControllor{
@Override
public void open() {
System.out.println("用意念打开");
}
}
package com.jsu.ch;
public abstract class TV {
public abstract void display(IControllor controllor);
}
package com.jsu.ch;
public class XiaoMiTV extends TV{
@Override
public void display(IControllor controllor){
controllor.open();
System.out.println("电视机屏幕打开");
}
}
package com.jsu.ch;
public class User {
private TV tv;
private IControllor controllor;
public User(IControllor controllor ,TV tv) {
this.tv = tv;
this.controllor = controllor;
}
public void oprate(IControllor controllor, TV tv){
tv.display(controllor);
}
}
package com.jsu.ch;
public class Client {
public static void main(String[] args) {
TV tv = new XiaoMiTV();
IControllor controllor = new RemoteControllor();
User user = new User(controllor,tv);
user.oprate(controllor,tv);
IControllor tyc = new ToyControllor();
user.oprate(tyc,tv);
IControllor rocketcontrollor = new RocketContollor();
user.oprate(rocketcontrollor,tv);
IControllor mind = new Mind();
user.oprate(mind,tv);
}
}
结果展示: