当前位置:网站首页>Combination mode -- stock speculation has been cut into leeks? Come and try this investment strategy!

Combination mode -- stock speculation has been cut into leeks? Come and try this investment strategy!

2022-06-24 20:31:00 zhanyd

Introduction

The stock market has been very hot recently , Xiaoshuai watched the people around him make a lot of money in the stock market , I feel itchy , Every day I am attracted by all kinds of news about making a fortune in stocks , Finally, I couldn't help entering the stock market , As a result, as the market fell several times , Not surprisingly, I became a leek , Finally frustrated .

Fortunately, Xiaoshuai happens to have a friend who has done a good job in investment , some IT Lao Zhang, technical director of the company , The average income in recent years has exceeded 20%, Xiaoshuai decided to ask him about his investment tips .

“ Lao Zhang , I heard that you have made a lot of money in the stock market in recent years , Can you teach me , I also want to learn to speculate in stocks .” Xiaoshuai learns from Lao Zhang .

Lao Zhang smiled :” Okay , But the investment is too complicated , You let me teach you , I can't start at once , What do you want to achieve through investment ?“

investment portfolio

“ No secret , I recently lost a lot of money in the stock market , The risk of stocks is too great . Is there an investment strategy , It can protect investors in any economic environment , Make everyone safe 、 Stable 、 Long term returns , At the same time, it's very simple , Even the most ignorant people can use it ?” Xiaoshuai asked eagerly .

“ There are , There is a very famous investor, brown, who put forward a plan called ‘ Permanent combination ’(The Permanent Portfolio) Asset allocation method , Just solved this problem .”

Lao Zhang continued :

The permanent portfolio divides the funds to be invested into four equal parts :25% Shares 、25% The national debt 、25% Cash and 25% Of gold .

But for a novice like you , It is not suitable for direct investment in individual stocks , I exchange stocks for index funds , Treasury bonds are exchanged for more flexible bond funds , Just buy paper gold for gold .

I will transform the permanent combination :25% Index fund of 、25% The bond fund 、25% Cash and 25% Paper gold .

I drew the structure of the portfolio , Xiaoshuai , Aren't you a programmer ? If I had to traverse every investment , Calculate the total amount of investment , Can you write it in code ?
 Insert picture description here

Traversal file

Xiaoshuai said :“ This is not hard to , In fact, this structure is very similar to the file system we often use , It's a tree structure , Calculating the total amount of funds is very similar to traversing the file , We can start by looking at how to traverse directories and files .”
 Insert picture description here
Directories are divided into folders and files , Folders are branches , Files are leaf nodes , We can define IBranch Represents the directory interface ,ILeaf Represents the file interface .

/** *  Directory Interface  */
public interface IBranch {
    
    /** *  Print directory name  * @param depth */
    void print(int depth);

    /** *  Add a directory  * @param branch */
    void add(IBranch branch);

    /** *  Add files  * @param leaf */
    void add(ILeaf leaf);

    /** *  Get contents of the directory  * @return */
    List<Object> getSubList();
}

/** *  Directory implementation class  */
public class Branch implements IBranch{
    

    List<Object> branchList = new ArrayList<Object>();

    String name;
    public Branch(String name) {
    
        this.name = name;
    }

    @Override
    public void print(int depth) {
    
        System.out.println(String.join("", Collections.nCopies(depth, "--")) 
        + name);
    }

    @Override
    public void add(IBranch branch) {
    
        branchList.add(branch);
    }

    @Override
    public void add(ILeaf leaf) {
    
        branchList.add(leaf);
    }

    @Override
    public List getSubList() {
    
        return branchList;
    }
}

/** *  File interface  */
public interface ILeaf {
    
    /** *  Print file name  * @param depth */
    void print(int depth);
}
/** *  File implementation class  */
public class Leaf implements ILeaf{
    

    String name;
    public Leaf(String name) {
    
        this.name = name;
    }

    @Override
    public void print(int depth) {
    
        System.out.println(String.join("", Collections.nCopies(depth, "--")) 
        + name);
    }
}

Construct directories and files , And then print :

public class BuildBranch {
    

    public static void main(String[] args) {
    
        IBranch root = new Branch(" root directory ");

        IBranch firstLevelBranch1 = new Branch("1 Level directory 1");
        ILeaf firstLevelBranch1File1 = new Leaf("1 Level directory 1- file 1");
        ILeaf firstLevelBranch1File2 = new Leaf("1 Level directory 1- file 2");
        firstLevelBranch1.add(firstLevelBranch1File1);
        firstLevelBranch1.add(firstLevelBranch1File2);
        //  hold 1 Level directory 1 Add to root 
        root.add(firstLevelBranch1);

        IBranch firstLevelBranch2 = new Branch("1 Level directory 2");
        ILeaf firstLevelBranch2File1 = new Leaf("1 Level directory 2- file 1");
        firstLevelBranch2.add(firstLevelBranch2File1);
        //  hold 1 Level directory 2 Add to root 
        root.add(firstLevelBranch2);

        IBranch secondLevelBranch1 = new Branch("2 Level directory 1");
        ILeaf secondLevelBranch1File1 = new Leaf("2 Level directory 1- file 1");
        ILeaf secondLevelBranch1File2 = new Leaf("2 Level directory 1- file 2");
        secondLevelBranch1.add(secondLevelBranch1File1);
        secondLevelBranch1.add(secondLevelBranch1File2);
        //  hold 2 Level directory added to 1 Level directory 
        firstLevelBranch1.add(secondLevelBranch1);

        root.print(0);
        //  Traverse all files and folders 
        printAll(root.getSubList(), 1);

    }

    /** *  Traverse all files and folders  * @param list * @param depth */
    public static void printAll(List<Object> list, int depth) {
    
        for(Object object : list) {
    
            if(object instanceof Leaf) {
    
                ((Leaf) object).print(depth);
            } else {
    
                ((Branch) object).print(depth);
                printAll(((Branch) object).getSubList(), depth + 2);
            }
        }
    }
}

Output results :

 root directory 
--1 Level directory 1
------1 Level directory 1- file 1
------1 Level directory 1- file 2
------2 Level directory 1
----------2 Level directory 1- file 1
----------2 Level directory 1- file 2
--1 Level directory 2
------1 Level directory 2- file 1

“ You see , That's it ”, Xiao Shuai smiles .

Lao Zhang saw the problem at a glance : You have two interfaces here IBranch and ILeaf, In fact, folders and files are regarded as two different things . When traversing the client, you need to distinguish between folders and files , First determine the type of object in the program , Then we can carry out different operations .

In fact, folders and files are part and whole , Is the relationship between the branches and leaves of a tree , Can we think of them as the same thing ? A leaf is a branch without child nodes , isn't it? ?
 Insert picture description here
Lao Zhang went on :” Can you find a way to make the client do not distinguish between folders and files , Let the client operate branches and leaves in the same way ? thus , The client call will be much simpler .“

Xiao Shuai said :“ This , I can't think of it at once , Lao Zhang, tell me about , How to write better ?”

Portfolio model

” In this case , There is a special design pattern , It's called combination mode , Let's have a look .“

Portfolio model : Organize a group of objects into a tree structure , To indicate that “ part - whole ” Hierarchical structure , Make the use of single object and composite object consistent .

That is to say, composite pattern regards single object and composite object as the same thing . In the above example, a file is a single object , A folder is a composite object .

Let's take a look at the class diagram :
 Insert picture description here

Traversal file

Let's modify the above code with the composite pattern :

/** *  Component class  */
public abstract class Component {
    

    /** *  Add the component  * @param */
    public void add(Component component) {
    
        throw new UnsupportedOperationException(" Add operation is not supported ");
    }

    /** *  Delete component  * @param component */
    public void remove(Component component) {
    
        throw new UnsupportedOperationException(" Delete operation is not supported ");
    }

    /** *  Print name  * @param depth */
    public abstract void print(int depth);
}
/** *  File class  */
public class File extends Component{
    

    String name;
    public File(String name) {
    
        this.name = name;
    }

    /** *  Print name  * @param depth */
    @Override
    public void print(int depth) {
    
        System.out.println(String.join("", Collections.nCopies(depth, "--")) 
        + name);
    }
}

/** *  Catalog class  */
public class Directory extends Component{
    

    List<Component> componentList = new ArrayList<Component>();

    String name;
    public Directory(String name) {
    
        this.name = name;
    }

    /** *  Add the component  * @param */
    @Override
    public void add(Component component) {
    
        componentList.add(component);
    }

    /** *  Delete component  * @param component */
    @Override
    public void remove(Component component) {
    
        componentList.remove(component);
    }

    /** *  Print name  * @param depth */
    @Override
    public void print(int depth) {
    
        System.out.println(String.join("", Collections.nCopies(depth, "--")) 
        + name);
        //  Recursive printing subcomponent 
        for (Component component : this.componentList) {
    
            component.print(depth + 2);
        }
    }
}
public class BuildDirectory {
    

    public static void main(String[] args) {
    
        Directory root = new Directory("root");

        Directory booksDirectory = new Directory("books");
        File coreJavaFile = new File("Java The core technology ");
        File codeCompleteFile = new File(" The code of ");
        booksDirectory.add(coreJavaFile);
        booksDirectory.add(codeCompleteFile);
        // books Add folder to root 
        root.add(booksDirectory);

        Directory picturesDirectory = new Directory("pictures");
        File pictures1 = new File(" Photo 1");
        File pictures2 = new File(" Photo 2");
        File pictures3 = new File(" Photo 3");
        picturesDirectory.add(pictures1);
        picturesDirectory.add(pictures2);
        picturesDirectory.add(pictures3);
        //  Delete photos 2
        picturesDirectory.remove(pictures2);
        //  hold pictures Add folder to root 
        root.add(picturesDirectory);

        Directory networkDirectory = new Directory("network");
        File computerNetworkingFile = new File(" computer network : top-down approach ");
        File tcpIpFile  = new File("TCP/IP Detailed explanation ");
        networkDirectory.add(computerNetworkingFile);
        networkDirectory.add(tcpIpFile);
        //  hold network Folder added to books Folder 
        booksDirectory.add(networkDirectory);

        root.print(0);
    }
}

Output :

root
----books
--------Java The core technology 
-------- The code of 
--------network
------------ computer network : top-down approach 
------------TCP/IP Detailed explanation 
----pictures
-------- Photo 1
-------- Photo 3

” You see , Does this look a lot simpler ?“ Lao Zhang said .

Xiaoshuai thought for a while and said :” Brevity is much more brevity , But I always feel a little strange ,add Methods and remove Why should a method throw an exception directly ?“
 Insert picture description here
Lao Zhang smiled and said : You observe very carefully , because add Methods and remove Method is a folder class specific method , There are no such methods in the file class , But in order to increase the transparency of the client , in other words , To make the folders and files look the same in the client's eyes , Let the folder class and file class have the same method .

however , To prevent misoperation of the client , Operate in the file class add and remove Method , So we are Component When declared in a class, an exception is thrown directly , This is also a protective measure for the program . And the folder class Directory In your own class, you will override add and remove Method to implement the functions of adding and deleting .

Xiaoshuai seems to suddenly understand :” So called transparency , By making component classes Component All operations involving both branch and leaf nodes , In this way, the client can regard the branch and leaf nodes as the same thing , That is, whether an element is a branch or leaf node is transparent to the client .

Lao Zhang added :” You're right , In order to achieve ’ transparency ‘, We lost a certain ’ Security ‘, For example, the client calls on the leaf node add and remove Method will throw an exception , however , If we emphasize ’ Security ‘ Will lose ’ transparency ‘, As in the initial example, we need to use instanceof To distinguish between different types .“
 Insert picture description here

Lao Zhang went on ,” You can't have both transparency and security , In the previous example, we chose transparency , Giving up security , Empathy , When investing , Low risk and high return cannot be achieved at the same time , Permanent portfolio is the tendency to control risk , To keep the principal , Give up a little high yield , You can't have both .“

” Okay , Now you use the combination mode to implement the code to calculate the total amount of permanent combination .“

” well , Look at me. .“

Calculate the total portfolio amount

/** *  Component class  */
public abstract class Component {
    

    /** *  Add the component  * @param */
    public void add(Component component) {
    
        throw new UnsupportedOperationException(" Add operation is not supported ");
    }

    /** *  Delete component  * @param component */
    public void remove(Component component) {
    
        throw new UnsupportedOperationException(" Delete operation is not supported ");
    }

    /** *  Print name  * @param depth */
    public abstract void print(int depth);

    /** *  Calculate the total amount  */
    public abstract int countSum();
}
/** *  investment projects  */
public class Project extends Component{
    

    String name;
    int price;
    public Project(String name, int price) {
    
        this.name = name;
        this.price = price;
    }

    /** *  Print name  * @param depth */
    @Override
    public void print(int depth) {
    
        System.out.println(String.join("", Collections.nCopies(depth, "--")) 
        + name + "  investment :" + price);
    }

    /** *  Return amount  * @return */
    @Override
    public int countSum() {
    
        return price;
    }
}
/** *  Investment category  */
public class Category extends Component{
    

    List<Component> componentList = new ArrayList<Component>();

    String name;
    public Category(String name) {
    
        this.name = name;
    }

    /** *  Add the component  * @param */
    @Override
    public void add(Component component) {
    
        componentList.add(component);
    }

    /** *  Delete component  * @param component */
    @Override
    public void remove(Component component) {
    
        componentList.remove(component);
    }

    /** *  Print name  * @param depth */
    @Override
    public void print(int depth) {
    
        System.out.println(String.join("", Collections.nCopies(depth, "--")) 
        + name);
        //  Recursive printing subcomponent 
        for (Component component : componentList) {
    
            component.print(depth + 2);
        }
    }

    /** *  Calculate the total amount  * @return */
    @Override
    public int countSum() {
    
        int sum = 0;
        for (Component component : componentList) {
    
            sum += component.countSum();
        }
        return sum;
    }
}
public class BuildProject {
    

    public static void main(String[] args) {
    
        Category root = new Category(" Permanent combination ");

        Project cash = new Project(" cash ",25000);
        Project paperGold = new Project(" Gold paper ", 25000);
        root.add(cash);
        root.add(paperGold);

        Category indexFund = new Category(" Index funds ");
        Project hushen300 = new Project(" Shanghai and Shenzhen 300",10000);
        Project zhongzheng500 = new Project(" personal witness 500",10000);
        Project chaungyeban = new Project(" Gem index ",5000);
        indexFund.add(hushen300);
        indexFund.add(zhongzheng500);
        indexFund.add(chaungyeban);
        //  Index funds are added to permanent portfolios 
        root.add(indexFund);

        Category bondFund = new Category(" Bond funds ");
        Project hybridBondFund = new Project(" Hybrid bond fund ", 15000);
        Project prueBondFund = new Project(" Pure bond fund ", 10000);
        Project corporateonds = new Project(" Corporate bonds ", 5000);
        bondFund.add(hybridBondFund);
        bondFund.add(prueBondFund);
        bondFund.add(corporateonds);
        //  Corporate bonds are too risky , Delete 
        bondFund.remove(corporateonds);
        //  hold pictures Add folder to root 
        root.add(bondFund);

        root.print(0);
        System.out.println(" Total investment amount :" + root.countSum());
    }
}

Output results :

 Permanent combination 
---- cash   investment :25000
---- Gold paper   investment :25000
---- Index funds 
-------- Shanghai and Shenzhen 300  investment :10000
-------- personal witness 500  investment :10000
-------- Gem index   investment :5000
---- Bond funds 
-------- Hybrid bond fund   investment :15000
-------- Pure bond fund   investment :10000
 Total investment amount :100000

“ Very good !”, Lao Zhang praised .

summary

Application scenarios of composite patterns :

  • If you need to implement a tree object structure , You can use combination patterns .
  • If you want client code to handle simple and complex elements in the same way , You can use this mode .

Advantages of the combined pattern :

  • Easy to use , You can make it easier to use complex tree structures with polymorphism and recursion .
  • Simplified client code , Clients can consistently use a composite structure and a single object , Usually users don't know ( Nor care ) Are you dealing with a single object or an entire composite structure .
  • Comply with opening and closing principle , No need to change existing code , You can add new elements to the app , Make it part of the object tree .

Disadvantages of combination mode :

  • For classes with different functions , Providing a common interface can be difficult , It will make it more difficult for the client to understand , It is very easy for the client to call the wrong operation .

Last

Lao Zhang patted Xiaoshuai and said : Risk can be well controlled according to this portfolio , And get a good return , It is very suitable for small white investors like you . You can also adjust it slightly according to your actual situation , such as , Now yu'e Bao is actually a monetary fund , The risk is very small , It's also very convenient to use , You can deposit your cash in yu'e Bao or other monetary funds, and you can also get a certain income .

If you have a high risk tolerance , The proportion of index funds can be appropriately raised , Put the cash , Gold paper , The proportion of bond funds has been lowered , Investment is an art , No best , Only the one that suits you best .

also , We'd better use fixed investment to buy funds , For example, every month 1000 Yuan , Don't buy all at once , Fixed investment can share the risk well , Will not let you buy at the highest point , After all, timing is very difficult .

” Thank you very much, Lao Zhang ! Today, I not only learned the knowledge of investment , I also learned a design pattern by the way , ha-ha !“ Xiaoshuai said happily .

原网站

版权声明
本文为[zhanyd]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211327028974.html