美文网首页
java8 一些设计模式的实现

java8 一些设计模式的实现

作者: 百炼 | 来源:发表于2019-05-26 18:49 被阅读0次

    Java8策略模式

    Validator接收一个接口,接口有一个方法。有一个方法的接口可看做函数接口。

    package lambdasinaction.chap8;
    
    public class StrategyMain {
    
        public static void main(String[] args) {
            // old school
            Validator v1 = new Validator(new IsNumeric());
            System.out.println(v1.validate("aaaa"));
            Validator v2 = new Validator(new IsAllLowerCase());
            System.out.println(v2.validate("bbbb"));
    
    
            // with lambdas
            Validator v3 = new Validator((String s) -> s.matches("\\d+"));
            System.out.println(v3.validate("aaaa"));
            Validator v4 = new Validator((String s) -> s.matches("[a-z]+"));
            System.out.println(v4.validate("bbbb"));
        }
    
        interface ValidationStrategy {
            /**
             * 执行方法
             *
             * @param s
             * @return
             */
            boolean execute(String s);
        }
    
        static private class IsAllLowerCase implements ValidationStrategy {
            @Override
            public boolean execute(String s) {
                return s.matches("[a-z]+");
            }
        }
    
        static private class IsNumeric implements ValidationStrategy {
            @Override
            public boolean execute(String s) {
                return s.matches("\\d+");
            }
        }
    
        static private class Validator {
            private final ValidationStrategy strategy;
    
            public Validator(ValidationStrategy v) {
                this.strategy = v;
            }
    
            public boolean validate(String s) {
                return strategy.execute(s);
            }
        }
    }
    

    Java 8 模板方法模式

    package lambdasinaction.chap8;
    
    /**
     * processCustomer方法搭建了在线银行算法的框架:获取客户提供的ID,然后提供服务让
     * 用户满意。不同的支行可以通过继承OnlineBanking类,对`makeCustomerHappy`方法提供差异化的实现。
     */
    abstract class OnlineBanking {
        public void processCustomer(int id){
            Customer c = Database.getCustomerWithId(id);
            makeCustomerHappy(c);
        }
        abstract void makeCustomerHappy(Customer c);
    
    
        // dummy Customer class
        static private class Customer {}
        // dummy Datbase class
        static private class Database{
            static Customer getCustomerWithId(int id){ return new Customer();}
        }
    }
    
    package lambdasinaction.chap8;
    
    import java.util.function.Consumer;
    
    public class OnlineBankingLambda {
        /**
         * 现在,你可以很方便地通过传递Lambda表达式,直接插入不同的行为,不再需要继承
         * OnlineBanking类了
         *
         * @param args
         */
        public static void main(String[] args) {
            new OnlineBankingLambda().
                    processCustomer(1337, (Customer c) -> System.out.println("Hello!"));
        }
    
        public void processCustomer(int id, Consumer<Customer> makeCustomerHappy) {
            Customer c = Database.getCustomerWithId(id);
            makeCustomerHappy.accept(c);
        }
    
        // dummy Customer class
        static private class Customer {
        }
    
        // dummy Database class
        static private class Database {
            static Customer getCustomerWithId(int id) {
                return new Customer();
            }
        }
    }
    

    责任链模式

    package lambdasinaction.chap8;
    
    import java.util.function.Function;
    import java.util.function.UnaryOperator;
    
    public class ChainOfResponsibilityMain {
    
        public static void main(String[] args) {
            ProcessingObject<String> p1 = new HeaderTextProcessing();
            ProcessingObject<String> p2 = new SpellCheckerProcessing();
            p1.setSuccessor(p2);
            String result1 = p1.handle("Aren't labdas really sexy?!!");
            System.out.println(result1);
    
    
            UnaryOperator<String> headerProcessing =
                    (String text) -> "From Raoul, Mario and Alan: " + text;
            UnaryOperator<String> spellCheckerProcessing =
                    (String text) -> text.replaceAll("labda", "lambda");
            Function<String, String> pipeline = headerProcessing.andThen(spellCheckerProcessing);
            String result2 = pipeline.apply("Aren't labdas really sexy?!!");
            System.out.println(result2);
        }
    
        static private abstract class ProcessingObject<T> {
            protected ProcessingObject<T> successor;
    
            public void setSuccessor(ProcessingObject<T> successor) {
                this.successor = successor;
            }
    
            public T handle(T input) {
                T r = handleWork(input);
                if (successor != null) {
                    return successor.handle(r);
                }
                return r;
            }
    
            abstract protected T handleWork(T input);
        }
    
        static private class HeaderTextProcessing
                extends ProcessingObject<String> {
            @Override
            public String handleWork(String text) {
                return "From Raoul, Mario and Alan: " + text;
            }
        }
    
        static private class SpellCheckerProcessing
                extends ProcessingObject<String> {
            @Override
            public String handleWork(String text) {
                return text.replaceAll("labda", "lambda");
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:java8 一些设计模式的实现

          本文链接:https://www.haomeiwen.com/subject/wvuftctx.html