Dimorphism is regulated by factors such as temperature, CO2 concentration, pH, and the levels of cysteine or other sulfhydryl-containing compounds. Gene expression regulation by such factors may produce this amazing change from yeast to mold and from mold to yeast.
Please do not suggest a "why?". The fungus is not making a rational decision. The general mechanism involves change in growth orientation from isotropic (uniform in all directions) to polarized (orientation to one direction).